Rails: i have a class method and i want to modify something of the instance
Rails: i have a class method and i want to modify something of the instance
something like this:
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
that is similar to the model classes:
# in the model
has_many :projects
开发者_开发问答
How do I do it?
EDIT:
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
You have to bite the bullet and learn ruby meta programming. There is a book on it.
http://pragprog.com/titles/ppmetr/metaprogramming-ruby
Here is one way to do it.
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
There are a few different ways to do this. Here is one:
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
精彩评论