2016-08-18 59 views
0

我的应用程序模型中有很多字符串,每个字符串不应该包含任何前导空格,尾随空格和重复空格。如何为Rails生成标准属性设置器

为了确保这一点,我会为每个属性单独的属性设置方法:

def label=(text) 
    write_attribute(:label, text.strip.squeeze(' ')) 
end 

def description=(text) 
    write_attribute(:description, text.strip.squeeze(' ')) 
end 

... 

应该有一个更优雅,烘干机的方式。包括一个支票零。

回答

1

在你的关注点中定义一个类方法,它创建所有需要的属性设置器。这个版本将返回nil所有空值,或对他人的修剪和挤压字符串:

module ApplicationModel 
    extend ActiveSupport::Concern 

    module ClassMethods 

    def set_trimmed(*attributes) 
     attributes.each do |a| 
     define_method "#{ a.to_s }=" do |t| 
      tt = t.blank? ? nil : t.strip.squeeze(' ') 
      write_attribute(a, tt) 
     end 
     end 
    end 

    end 
end 

,并简单地列出要定义这个属性的setter模型中的属性(别忘了包括上述模块):

include ApplicationModel 

set_trimmed :label, :description, :postal_address, :street_address, ... 
相关问题