Phlip
4/24/2008 2:43:00 PM
Stefan Kroes wrote:
> Hi all,
>
> I'm pretty new to Ruby and RoR but I'm trying to learn for a large
> project. I wrote the following method in one of my models but it can't
> be the right way to do this because ruby should be able to do it way
> more concisely. Can you tell me of a better way?
Firstly, write unit tests covering each of its branches. That way, you can do
the edits I'm about to do, but one at a time, and pass all the tests after each one.
> def name
> if !@name
> property = content_properties.find_by_key('name')
> if property
> @name = property.value
> else
> @name = ""
> end
> else
> @name
> end
> end
Good design is about merging redundant things. Your @name appears too many
times, so we will have a crack at that.
def name
@name ||= ( property = content_properties.find_by_key('name')
property ? property.value : '' )
end
Yes, you can put a linefeed (or a ; ) inside parens. They return their last
statement's value, just like a function returns its last statement's value.
Next, ||= is a common idiom for "surprise assignment". If the left argument is a
nil or false variable, the right side is evaluated and assigned.
And, finally, @name is nil if it's not declared yet.
--
Phlip