Ruby on rails 自定义方法如何适用于各种模型
我有以下方法称为capitaleachword。在这个方法中有一个名为company的属性Ruby on rails 自定义方法如何适用于各种模型,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有以下方法称为capitaleachword。在这个方法中有一个名为company的属性 class BusCompany < ActiveRecord::Base attr_accessible :company before_save :capitalizeEachWord validates :company,presence: true, uniqueness: { case_sensitive: false },
class BusCompany < ActiveRecord::Base
attr_accessible :company
before_save :capitalizeEachWord
validates :company,presence: true,
uniqueness: { case_sensitive: false },
format: /^([a-zA-z0-9]+\s?){1,}$/
def capitalizeEachWord
self.company=self.company.downcase.split.map(&:capitalize).join(' ')
end
end
我希望此方法不直接使用属性company,而是将此属性作为参数接收,因为它不依赖于模型BusCompany。如下所示。问题是,我将在各种模型中使用这种方法,并且不希望在每个模型中编写它,而是使用继承
class BusCompany < ActiveRecord::Base
attr_accessible :company
before_save :capitalizeEachWord(self.company)
validates :company,presence: true,
uniqueness: { case_sensitive: false },
format: /^([a-zA-z0-9]+\s?){1,}$/
def capitalizeEachWord(attribute)
self.attribute=self.attribute.downcase.split.map(&:capitalize).join(' ')
end
end
首先,我建议您重写公司的setter,而不是使用容易出错的回调,如下所示:
class BusCompany < ActiveRecord::Base
# you can also use #titleize instead of capitalize each word
# also use try, in case `arg` is nil
def company=(arg)
super arg.try(:titleize)
end
end
最后,将其扩展到所需的模型中:
class BusCompany
extend CapitalizedSetter
capitalized_setter :company
end
将以下代码添加到config/initializers/capitaler.rb中 然后在你的课堂上:
class BusCompany < ActiveRecord::Base
include Capitalizer
capitalize :company
...
end
spickermann如果用户写FERNANDO DANIEL,我必须使用strip来消除空白字符串结尾处的空格,然后使用titleizenicooga如果用户写FERNANDO DANIEL,我必须使用strip来消除空白字符串结尾处的空格,然后使用titleize
module Capitalizer
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def capitalize(*attributes)
@attributes_to_capitalize = attributes
before_save :capitalize_each_word
end
def attributes_to_capitalize
Array.new(@attributes_to_capitalize)
end
end
def capitalize_each_word
self.class.attributes_to_capitalize.each do |attr|
if value = send(attr)
self.send("#{attr}=", value.strip.titleize)
end
end
end
end
class BusCompany < ActiveRecord::Base
include Capitalizer
capitalize :company
...
end