61dae6f655999810e6cf1ce3b106366e

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?

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 !

61dae6f655999810e6cf1ce3b106366e

Aditya

February 28, 2008, February 28, 2008 16:14, permalink

No rating. Login to rate!

orm activerecord before_save

6c452e0114832b067300e23b6f83c8e8

Bobby Uhlenbrock

February 28, 2008, February 28, 2008 17:46, permalink

2 ratings. Login to rate!

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
63b22ac9bff0cd55d8a91da4dbf00693

Dan Kubb

February 28, 2008, February 28, 2008 18:22, permalink

1 rating. Login to rate!

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
61dae6f655999810e6cf1ce3b106366e

Aditya

February 29, 2008, February 29, 2008 07:44, permalink

No rating. Login to rate!

Thanks guys! I just needed reminding that AR models can be treated like a hash. Cool and wonderful!

Your refactoring





Format Copy from initial code

or Cancel