Hobo Cookbook

View Source

Manual

Last updated: May 12, 2009

HoboSupport

HoboSupport is a mixed bag of core ruby extensions that have been extracted from the Hobo project

>> HoboSupport::VERSION
=> "1.0.2"

Contents

Object extensions

Object#is_one_of?

Like is_a? but multiple types to be checked in one go

>> "foo".is_one_of?(String, Symbol)
=> true
>> :foo.is_one_of?(String, Symbol)
=> true
>> 1.is_one_of?(String, Symbol)
=> false

Method call extensions

We have the ”.” operator to call methods on objects. These extensions introduce two “special dots”.

Object#_?

._?.” only calls the method if the receiver is not nil. Otherwise it returns nil. So x._?.method(*args) is equivalent to (nil == x ? nil : x.method(*args)).

>> "foo"._?.length
=> 3
>> nil._?.length
=> nil

When the receiver is nil, any method with any arguments will return nil. You can use Ruby’s || idiom to provide a different value when nil.

>> expires = nil
>> expires._?.to_s( :default ) || "never"
=> "never"

Note that _? should always be followed by a method call. It is not intended to store the intermediate result. Don’t do this!

intermediate = nil._?

Object#try

.try” only calls the method if the receiver responds to that method. Otherwise it returns nil. So x.try.method(*args) is equivalent to (x.respond_to?(:method) ? x.method(*args) : nil).

>> "foo".try.reverse
=> "oof"
>> :foo.try.reverse
=> nil

What’s the difference?

Use _? when you want to call a method but you know the receiver may be nil. Use try when you want to call a method but you know the receiver may not respond to it. For instance, you may use try to call a Rails 2.3 function that doesn’t exist on Rails 2.2. Note that nil responds to some functions that may surprise you.

>> nil.try.to_i
=> 0
>> nil._?.to_i
=> nil