【发布时间】:2015-07-16 20:30:40
【问题描述】:
我创建了一些模型回调方法,这些方法可以在每次创建、更改或删除文件时为属性添加时间戳。
我想知道是否有更优雅的方式来编写这些回调,而不必重复类似的方法代码五次:
before_update :quote_file_updated?, on: [:create, :update], if: ->(r) { r.quote_file_changed? }
before_update :survey_file_updated?, on: [:create, :update], if: ->(r) { r.survey_file_changed? }
before_update :sign_off_sheet_file_updated?, on: [:create, :update], if: ->(r) { r.sign_off_sheet_file_changed? }
before_update :invoice_file_updated?, on: [:create, :update], if: ->(r) { r.invoice_file_changed? }
before_update :cert_file_updated?, on: [:create, :update], if: ->(r) { r.cert_file_changed? }
def quote_file_updated?
self.remove_quote_file ? self.quote_file_date = nil : self.quote_file_date = Time.now
end
def survey_file_updated?
self.remove_survey_file ? self.survey_file_date = nil : self.survey_file_date = Time.now
end
def sign_off_sheet_file_updated?
self.remove_sign_off_sheet_file ? self.sign_off_sheet_file_date = nil : self.sign_off_sheet_file_date = Time.now
end
def invoice_file_updated?
self.remove_invoice_file ? self.invoice_file_date = nil : self.invoice_file_date = Time.now
end
def cert_file_updated?
self.remove_cert_file ? self.cert_file_date = nil : self.cert_file_date = Time.now
end
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 methods callback