我無法從我在Google上閱讀的內容中瞭解到這一點,但是我想創建一個gem,當它保存時會改變模塊的行爲,但我不知道如何做這個。我如何在Gem中定義一個覆蓋模型保存方法的保存方法?Gem,導軌的自定義保存方法
更新:我發現Rails 3: alias_method_chain still used?,我將檢查。看來,alias_method_chain已經廢棄了Rails的3
我無法從我在Google上閱讀的內容中瞭解到這一點,但是我想創建一個gem,當它保存時會改變模塊的行爲,但我不知道如何做這個。我如何在Gem中定義一個覆蓋模型保存方法的保存方法?Gem,導軌的自定義保存方法
更新:我發現Rails 3: alias_method_chain still used?,我將檢查。看來,alias_method_chain已經廢棄了Rails的3
我寧願這樣做:
module YourModule
def self.included(base)
base.extend(InstanceMethods)
end
module InstanceMethods
def save
# Your behavior here
super # Use this if you want to call the old save method
end
end
end
然後在模型中:
class User < ActiveRecord::Base
include YourModule
end
希望它有幫助:)
使用alias_method_chain:
module YourModule
def self.included(base)
base.send(:include, YourModule::InstanceMethods)
base.alias_method_chain :save, :action
end
module InstanceMethods
def save_with_action
# do something here
save_without_action
end
end
end
然後您在您的AR對象模塊:
class User < ActiveRecord::Base
include YourModule
end
我不確定,但我認爲alias_method_chain已被棄用與Rails 3. http://stackoverflow.com/questions/3689736/rails-3-alias-method-chain-still-used –
即使alias_method_chain本身已被棄用,你可以仍然做同樣的行爲。而不是'base.alias_method_chain',你只需要兩次'base.alias_method'調用。 – YenTheFirst
改變行爲如何?像gsub其中一個屬性或者是這個效果的東西? – pjammer
例如,檢查是否...如果假中止,則保存如果不繼續 –
您的示例可以通過驗證來完成。如果你的行爲很簡單,你也可以使用'before_save'回調鉤子。你是否想要做比這更瘋狂的事情? – YenTheFirst