1 2 3 4 5 6 7 8 9 10 11
before_same :titlecase_fields def titlecase_fields self.name = self.name.titlecase unless self.name.blank? self.f_name = self.f_name.titlecase unless self.f_name.blank? self.m_name = self.m_name.titlecase unless self.m_name.blank? self.f_desg = self.f_desg.titlecase unless self.f_desg.blank? self.m_desg = self.m_desg.titlecase unless self.m_desg.blank? self.house_name = self.house_name.titlecase unless self.house_name.blank? return true end
Refactorings
No refactoring yet !
Bobby Uhlenbrock
February 28, 2008, February 28, 2008 17:46, permalink
I hope this makes sense. I am creating an array with the names of the attributes to be titlecased, then iterating through the attributes of the model to find matches. attribute_present? is from ActiveRecord::Base and makes sure that the attribute has been set and is not empty.
Model
1 2 3 4 5 6 7
before_save :titlecase_fields def titlecase_fields fields = ["name", "f_name", "m_name"] self.attributes.each { |key,value| self[key] = value.titlecase if self.attribute_present?(key) && fields.include?(key) } end
Dan Kubb
February 28, 2008, February 28, 2008 18:22, permalink
This iterates over just the attributes, and titleizes each attribute that is present (non-blank).
1 2 3 4 5 6 7
before_save :titlecase_fields def titlecase_fields %w[ name f_name m_name f_desg m_desg house_name ].each do |attribute| self[attribute] = self[attribute].titleize if attribute_present?(attribute) end end
I'd like to run titlecase method on a bunch of activerecord attributes before save (if they are not blank).
Whats a Rails Respectable way to do this?
I know i can put a list of strings in an array and loop over it using each. but how do i take the string and convert it into an attribute on self/model?