Rails 3.1模板处理程序

时间:2011-08-11 22:10:35

标签: ruby-on-rails ruby actionview mustache

我有一个ruby gem,poirot,可以在Rails中使用小胡子模板。我的模板处理程序是从ActionView :: Template :: Handler扩展,但是在Rails 3.1中似乎不推荐使用它。

我已经重新考虑了处理程序以遵守弃用警告。在执行此操作时,我现在无法将本地或视图上下文传递给模板。我似乎无法找到如何使用Rails 3.1。

module Poirot
  class Handler

    attr_reader :template

    def initialize(template)
      @template = template
    end

    def self.call(template, *args)
      self.new(template).call
    end

    def call
      view_path = "#{template.virtual_path}_view"
      abs_view_path = Rails.root.join('app/views', view_path)
      view_class = begin
        view_path.classify.constantize
      rescue NameError => e
        Poirot::View
      end
      "#{view_class}.new(self, '#{template.source.gsub(/'/, "\\\\'")}').render.html_safe"
    end
  end
end

在上面的处理程序代码中,我传递了模板,它是ActionView :: Template的一个实例。但我不知道如何获取视图上下文,其中应该包括本地人等

有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:0)

好的,我有一个解决方案,我不确定它是最好的,对我来说感觉有点哈哈!

在我的视图课程中,我设法通过执行以下操作来访问本地人员:

locals = view_context.send(:view_renderer).send(:_partial_renderer).instance_variable_get("@locals") || {}

这看起来有点乱,因为view_renderer和_partial_renderer都是私有的,并且没有适当的本地人访问者ivar。

我仍然希望有更好的方法来做到这一点!

答案 1 :(得分:0)

我花了大约4个小时调查源代码以找到解决方案,现在看起来非常简单:

只需添加“local_assigns”即可评估并使用它。

例如:

"#{view_class}.new(self, '#{template.source.gsub(/'/, "\\\\'")}', local_assigns).render.html_safe"

此字符串将在模块上下文中进行评估 - ActionView::CompiledTemplates并且local_assigns可在此处访问。