2
我只是抓住了Rails中的疑慮,並試圖爲ActiveRecord類實現簡單的日誌記錄。在那裏,我想定義應該進入日誌的字段,並在保存後自動寫入日誌。Rails:關注before_filter類型的方法
我有這樣的:
#logable.rb (the concern)
module Logable
extend ActiveSupport::Concern
@field = nil
module ClassMethods
def set_log_field(field)
@feild = field
end
end
def print_log
p "LOGGING: #{self[@index.to_s]}"
end
end
#houses.rb (the model using the concern)
class House < ActiveRecord::Base
include Logable
after_save :print_log
set_log_field :id
end
不幸的是,呼叫set_log_field沒有效果 - 或者更確切地說,給定的值不使其print_log。 我在做什麼錯?
感謝您的幫助!
太棒了,那有效!你能否解釋在包含的do ... end中定義的方法與每個塊之外的方法(當然是在模塊中)之間有什麼區別? – Daniel
@DanielArnreich我已經用最好的鏈接更新了我的答案,他們對你提出的差異有很好的例子。 – dimakura