Rails:我有一个类方法,我想修改一些实例
类似的东西:
class Test < Main
template :box
def test
# here I want to access the template name, that is box
end
end
class Main
def initialize
end
def self.template(name)
# here I have to save somehow the template name
# remember is not an instance.
end
end
类似于模型类:
# in the model
has_many :projects
我该怎么做?
编辑:
class Main
def self.template(name)
@name = name
end
def template
Main.instance_eval { @name }
end
end
class Test < Main
template 6
end
t = Test.new.template
t # t must be 6
答案 0 :(得分:1)
有几种不同的方法可以做到这一点。这是一个:
class Main
def self.template(name)
@name = name
end
end
class Test < Main
def test
Main.instance_eval { @name }
end
end
Main.template 5
Test.new.test
==> 5
答案 1 :(得分:1)
你必须咬紧牙关学习ruby元编程。有一本书就可以了。
http://pragprog.com/titles/ppmetr/metaprogramming-ruby
这是一种方法。
class M
def self.template(arg)
define_method(:template) do
arg
end
end
end
class T < M
template 6
end
t = T.new
puts t.template