Forum: Ruby on Rails Best way to automatically format model entries

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
71ee1809f53df0a2b4dac0530f630933?d=identicon&s=25 Richard Schneeman (snowmaninthesun)
on 2008-12-26 23:49
Using rails 2.1.0 I have a really nasty bit of code in my controller in
my create action that i would like to move to my model:

params[:phrase]["word"] = params[:phrase]["word"].strip.squeeze(" ")
        if params[:phrase]["word"] != nil

params[:phrase]["second_word"] =
params[:phrase]["second_word"].strip.squeeze(" ")      if
params[:phrase]["second_word"] != nil

params[:phrase]["third_word"] =
params[:phrase]["third_word"].strip.squeeze(" ")       if
params[:phrase]["third_word"] != nil

@phrase = Phrase.new(params[:phrase])


What would be the best way to do this, I was thinking of putting it
inside of a :before_save function. But i've never written one before and
didn't know how to get the parameters from my recently saved phrase( how
do I tell it to use the phrase i just created? @phrase.word ? ). What
would you recommend??
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2008-12-28 21:26
(Received via mailing list)
Richard Schneeman wrote:
> params[:phrase]["third_word"] =
> would you recommend??
Put something like this in a file in the lib directory:

class ActiveRecord::Base
   def self.blacken_attrs(*attrs)
     before_validation <<-END
       #{attrs.inspect}.each do |attr|
         if v = send(attr)
           v.strip!
           v.squeeze!(' ')
         end
       end
     END
   end
end

Then in the Phrase model write

blacken_attrs :word, :second_word, :third_word

--
Rails Wheels - Find Plugins, List & Sell Plugins -
http://railswheels.com
This topic is locked and can not be replied to.