2010-06-01 40 views
1

的Rails的东西:我有一个类的方法,我想修改实例的东西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

您是否考虑过将您的一些问题标记为已回答? – DJTripleThreat 2010-06-06 08:56:27

回答

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 
+0

谢谢,但它不完全是我的意思..“Main.template 5”必须进入测试<主类(记住,将有test01,test02类,他们应该有不同的模板名称,并且不能共享!如果我在test01中更改,应该不会在test02中更改,就像在模型中一样)。类“test”必须在Main类中工作。谢谢;)看在编辑(上) – 2010-06-02 21:20:40

相关问题