Find directory of subclass before initialization to configure dry-view paths

119 views Asked by At

I'm using dry-views in multiple Rails engines and I have to duplicate the configuration in every subclass.

class BaseView < Dry::View::Controller
  configure do |c|
    c.paths = [File.join(__dir__, 'templates')]
  end
end

class SubView < BaseView
  configure do |c|
    c.paths = [File.join(__dir__, 'templates')] # todo: remove me
  end
end

The reason is, that my views can be deeply nested in a sub folder of app ie.:

app/
app/foo/index.rb
app/foo/templates/index.html.erb
app/foo/bar/show.rb
app/foo/bar/templates/show.html.erb

Additionally the BaseView class does not live in the same gem in most of the cases.

If I delete the configure block from the SubView class, the template is not found anymore. The __dir__ variable contains the directory path of the BaseView class.

I've tried to implement a after initialization method in the base class that has access to the directory of the subclass. But at that point the configuration is not possible anymore due to restrictions in dry-rb configuration. The configuration must happen before initialization.

The only solution I could come up with is to duplicate the configure block in each class, or have a gem/engine specific parent class that configures all possible template paths.

The usual approach of looking for the directory of a certain method that is implemented in each subclass does also not work in this case, since most views don't even define methods.

Is there better ways to access the directory of a given class during the load phase of this class in a method of the parent class?

1

There are 1 answers

2
Aleksei Matiushkin On
class BaseView < Dry::View::Controller
  def self.inherited(child)
    child.class_eval do
      configure do |c|
        c.paths = [File.join(__dir__, 'templates')]
      end
    end
  end
end

Callback Class#inherited.