The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
The opposite of blank? in Rails

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Florian Frank

Posts: 48
Nickname: ffrank
Registered: Dec, 2005

Florian Frank is a humanoid life-form, living on the third planet of the solar system.
The opposite of blank? in Rails Posted: Mar 1, 2007 4:29 AM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Florian Frank
Latest Posts From The Rubylution: Tag Ruby

Advertisement

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:

<%= foo.category.name rescue '-' %>

Read: The opposite of blank? in Rails

Topic: rcov 0.8.0 (Ruby code coverage): new output modes, fix for RSpec woes, superior emacs integration Previous Topic   Next Topic Topic: burnout and the late night rant

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use