0

我在多个 Rails 引擎中使用干视图,我必须在每个子类中复制配置。

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

原因是,我的观点可以深深地嵌套在appie. 的子文件夹中:

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 中。

如果我从类中删除该configureSubView,则不再找到该模板。该__dir__变量包含BaseView类的目录路径。

我试图在可以访问子类目录的基类中实现初始化后的方法。但此时由于配置限制,无法再进行dry-rb配置。配置必须在初始化之前进行。

我能想出的唯一解决方案是configure在每个类中复制块,或者有一个配置所有可能模板路径的 gem/engine 特定的父类。

在这种情况下,查找在每个子类中实现的某个方法的目录的常用方法在这种情况下也不起作用,因为大多数视图甚至没有定义方法。

有没有更好的方法在这个类的加载阶段在父类的方法中访问给定类的目录?

4

1 回答 1

1
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

于 2017-12-06T17:38:55.883 回答