Rails用self调用一个方法



Rails 4.1Ruby 2.0Windows 8.1

我的应用程序中有三个不同的模型,我需要在保存之前"消毒"电话号码和电子邮件。我可以在每个模型中做这样的事情吗?

 before_save :sanitize_phones_and_email

和helpers/application_helper.rb:

def sanitize_phones_and_email
  (self.email = email.downcase) if attribute_present?("email")
  (self.work_phone = phony_normalize work_phone, :default_country_code => 'US') if   attribute_present?("work_phone")
  (self.mobile_phone = phony_normalize mobile_phone, :default_country_code => 'US') if attribute_present?("mobile_phone")
  (self.fax_phone = phony_normalize fax_phone, :default_country_code => 'US') if attribute_present?("fax_phone")
  (self.other_phone = phony_normalize other_phone, :default_country_code => 'US') if attribute_present?("other_phone")
end

"self"会被Rails正确处理吗?(因为我不能把它作为参数传递给方法)

helper应该只用于将在视图中使用的方法。

回答你的问题,不,这将不起作用。你不能在你的模型中使用视图助手。

如果"sanitize_phones_and_email"在你使用它的每个模型中都被定义,它将正常工作("self"将引用该模型的实例)。

如果你对DRY模型感兴趣,一个简单而有效的方法(但不一定是最好的面向对象实践)是使用mixin。当您包含mixin时,该模块中的方法自动成为类的实例方法。"self"将指向包含它的对象。

例如,在Rails 4中,你可以把这样的东西放在你的"关注点"文件夹中:

app/模型/问题/sanitzable.rb:

module Sanitizable
  extend ActiveSupport::Concern
  included do
    before_save :sanitize_phones_and_email
  end
  def sanitize_phones_and_email
    (self.email = email.downcase) if attribute_present?("email")
    (self.work_phone = phony_normalize work_phone, :default_country_code => 'US') if      attribute_present?("work_phone")
    (self.mobile_phone = phony_normalize mobile_phone, :default_country_code => 'US') if attribute_present?("mobile_phone")
    (self.fax_phone = phony_normalize fax_phone, :default_country_code => 'US') if attribute_present?("fax_phone")
    (self.other_phone = phony_normalize other_phone, :default_country_code => 'US') if attribute_present?("other_phone")
  end
end

app/模型/my_model.rb

class MyModel < ActiveRecord::Base
  include Sanitizable    
end

最新更新