to_s FTDRY
Wijnand Wiersma do 02 sep 10
Here is just a quick tip: define more to_s methods on your models to DRY up you views. It’s a very Ruby thing to do and if you keep this method fairly on top of your classes it won’t be very confusing for other developers.
For one project I have 3 models: include, exclude and split. When I want to display them I only want to show the only defined property they have: path
I display them regularly in views and it gets used in background processes where it is concatenated into a bigger string.
So instead of writing include.path everytime I went for this approach:
def to_s path end
From now on I can do something like this in my views:
<li><%= include %></li>
And where it gets concatenated:
"#{first_include} something here #{second_include}"or a array gets joined:
includes.join(" ")
Another nice example might be a person class where you display the persons name regularly in views. If you keep the parts of the name in multiple properties you are getting a bigger win:
def name [first_name, last_name_prefix, last_name].reject{|x|x.blank?}.join ' ' end
So if you display an object as a string a lot defining a to_s method and just put in your plain object in your view will certainly a nice way to get more DRY.
Gepost in hor | 0 reacties
Welcome to Holland On Rails
This weblog is the official Ruby techblog from the guys at Holder, a Ruby development company. Holder is also the company behind the RubyAndRails Europe Conference in Amsterdam.Recente Jobs
Bekijk alle jobs »»
Gereedschapskist
Onmisbare tools vooriedere developer!
- Ruby On Rails
Framework voor de web 2.0 developer. Eindelijk vooruitgang! - TextMate
Editor for true pro's
Typ, tab, top :-)
Nee, niet voor Win. - Made On A Mac
En nou is het over met die saaie grijze Windows bak van je!
Auteurs op deze site
Chris Obdam
'Less is more' evangelist, past dit ook dagelijks toe op zijn tandenborstel.Chiel Wester
Snelheidswonder op Ruby wielen. Leuk om mee te pair-programmen ;-)
Plaats je reactie