如何通过模块将值分配给类中包含的方法?

时间:2019-06-10 20:38:26

标签: ruby-on-rails ruby ruby-on-rails-5.2

module MyModule
   def method1
     @my_value
   end

   def method2
     "#{method1} is another method"
   end
end

class MyClass
    include MyModule
    @my_value = 'Method1' 
end

puts MyClass.new().method2
>>   is another method

如何获取分配给类中方法的值?如您所见,@ my_value为零。

1 个答案:

答案 0 :(得分:1)

module MyModule
  def set_my_value(val)
    define_method :my_value do
      val
    end
  end

  def method1
    my_value
  end

  def method2
    "#{method1} is another method"
  end
end

class MyClass
  include MyModule
  extend MyModule
  @my_value = 'Method1'
  set_my_value 'Method1'
end

您可以这样,rails大量使用这种方式,并且当您将模块包含到类中时,它将成为此类的继承层次结构中的父级,因此您不能像以前那样直接访问它的实例变量(在类主体中)访问它,您需要从一个内部方法

module MyModule
  def method1
    @my_value
  end

  def method2
    "#{method1} is another method"
  end
end

class MyClass
  include MyModule
  def initialize
    @my_value = 'Method1'
  end
end

puts MyClass.new().method2  

您在代码中定义的是类实例变量,而不是您要修改的实例变量