2016-08-18 57 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, ... 
相關問題