2010-01-03 78 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

相關問題