2010-01-03 32 views
3

我创建了一个Model类,其中我基于User(从Model继承)中调用的方法(属性)定义方法。问题是我无法重写由define_method定义的方法,并调用super传递给定义的方法。我想这是因为定义的方法被添加到用户本身,而不是添加到模型,所以它在超类(即模型)中实际上没有方法。调用super由define_method定义的方法

我想这样做的原因是因为大多数属性应直接保存到数据库中,而某些属性(如密码)需要一些额外的处理。

class Model 
    def self.attribute(name) 
    define_method(name) do 
     self 
    end 
    end 
end 

class User < Model 
    attribute :password 
end 

class User2 < Model 
    attribute :password 

    def password 
    super 
    end 
end 

@user = User.new 
puts @user.password # => <User:0x00000100845540> 

@user2 = User2.new 
puts @user2.password 
# define_super.rb:17:in `password': super: no superclass method 
# `password' for #<User2:0x00000100845578> (NoMethodError) 
# from define_super.rb:25:in `<main>' 

有没有什么办法可以改变代码来使它工作?我需要一种方法来覆盖动态创建的方法。

回答

9

定义的superclass方法:

class Model 
    def self.attribute(name) 
    superclass.send :define_method, name do 
     self 
    end 
    end 
end 
+0

谢谢。那正是我需要的。 – 2010-01-03 13:53:59

+0

如果这就是你需要的,你应该选择答案。晚得多(7年以上)比从未。 :-) – 2017-03-22 19:16:23

3

的方式Rails的涉及这是有多种方式来获得属性。其中之一是(按惯例)从未被覆盖,因此它可以在您定义的方法中使用:

# This method is never overridden, but also rarely used as a public method 
def[](key) 
    # Returns value of `key` attribute 
end 

# This is the effective default implementation of an attribute 
def att1 
    self[:att1] 
end 

# This shows how you can have custom logic but still access the underlying value 
def att2 
    self[:att2] unless self[:att2].empty? 
end 
+0

或类似的:'a = Document.last,a.read_attribute(:name)',你也可以'a.write_attribute(:name,'fooo')' – equivalent8 2013-01-14 10:57:27

相关问题