This post originated from an RSS feed registered with Ruby Buzz
by Florian Frank.
Original Post: The opposite of blank? in Rails
Feed Title: The Rubylution: Tag Ruby
Feed URL: http://rubylution.ping.de/xml/rss/tag/ruby/feed.xml
Feed Description: Starts… Now.
Ruby on Rails has a core extension that defines blank? for all objects, that are considered to be nil? or empty? and so on. (I think this idea originally came up on the ruby-talk mailing list.)
I often want to use the following code to save a few lines:
if foo = params[:foo]
# do something with foo
end
Of course this cannot make use of blank? and therefore only works if params[:foo] really is nil. So what am I to do?
It's quite easy to define a Object#full? method like this:
class ::Object
def full?
blank? ? nil : self
end
end
Now it's easy to have the intended semantics:
if foo = params[:foo].full?
# do something with foo
end
And the code talks equally well to me.
Ok, there is also the situation, where you want to display an associated object in a Rails view, but it can also be nil. It would be nice to be able to pass a block to full? like that:
<%= foo.category.full? { |c| c.name } || '-' %>
This is easy to be added to our full? method:
class ::Object
def full?
f = blank? ? nil : self
if block_given? and f
yield f
else
f
end
end
end
This is reasonably short (without much repetition like if and ?:) and much cleaner and less dangerous than to use rescue: