如何将var传递给包含的模块?

时间:2015-08-08 04:44:31

标签: ruby class module include

可能很简单,但我对使用ruby include感到有些困惑:

app.rb:

class Controller
  @template_ext = '.slim'
  def template_ext
    '.slim'
  end
  include RenderingHelpers
end

rendering_helpers.rb:

module RenderingHelpers

  def render(resp_code=200)
    puts @template_ext # Breaks
    puts template_ext() # => '.slim'
    # Not important: 
    path = File.expand_path(find_template())
    tilt = Tilt.new(find_template()).render(self)
    Rack::Response.new tilt, resp_code
  end

我有点困惑为什么方法template_ext()有效,但@template_ext没有?

3 个答案:

答案 0 :(得分:1)

@ sigil开头的变量是实例变量。实例变量属于实例(对象),这就是为什么它们被称为实例变量(duh!)。

在这种情况下,您有两个对象ControllerRenderingHelpers的实例正在调用render。它们是两个不同的对象,因此,它们各自都有自己独特的实例变量集。

答案 1 :(得分:0)

对于变量,您可以将变量作为类变量 -

 class Controller
   @@template_ext = '.slim'
   def template_ext
     '.slim'
   end
   include RenderingHelpers
 end

或者你可以做 -

module RenderingHelpers
  extend ActiveSupport::Concern
  included do 
    @template_ext = '.slim'
  end

  def render(resp_code=200)
    puts @template_ext # Breaks
    puts template_ext() # => '.slim'
    # Not important: 
    path = File.expand_path(find_template())
    tilt = Tilt.new(find_template()).render(self)
    Rack::Response.new tilt, resp_code
  end    
end

答案 2 :(得分:0)

在您的示例中,@template_ext变量实际上是一个类级实例变量,这使得render等实例方法无法访问它。

您实际想要做的只是删除@template_ext作业并坚持您的方法template_ext

This can teach you more about how Modules in Ruby work

相关问题