我在多个Rails引擎中使用dry-views,并且我必须在每个子类中复制配置。
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原因是,我的视图可以深度嵌套在app的子文件夹中,即:
app/
app/foo/index.rb
app/foo/templates/index.html.erb
app/foo/bar/show.rb
app/foo/bar/templates/show.html.erb此外,在大多数情况下,BaseView类并不在同一个gem中。
如果我从SubView类中删除configure块,则不再找到该模板。__dir__变量包含BaseView类的目录路径。
我尝试在基类中实现一个初始化后的方法,它可以访问子类的目录。但在这一点上,由于dry-rb配置中的限制,该配置不再可能。必须在初始化之前进行配置。
我能想到的唯一解决方案是在每个类中复制configure块,或者有一个特定于gem/engine的父类来配置所有可能的模板路径。
查找在每个子类中实现的某个方法的目录的通常方法在这种情况下也不起作用,因为大多数视图甚至没有定义方法。
在父类的方法中,在这个类的加载阶段,有没有更好的方法来访问给定类的目录?
发布于 2017-12-07 01:38:56
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回调Class#inherited。
https://stackoverflow.com/questions/47680139
复制相似问题