Skip to content

Instantly share code, notes, and snippets.

@sfilatov
Created August 11, 2011 12:55
Show Gist options
  • Save sfilatov/1139569 to your computer and use it in GitHub Desktop.
Save sfilatov/1139569 to your computer and use it in GitHub Desktop.
Object#chain
# sort by price after sort by date if active projects listed
collection.sort_by_date_asc.chain(|c| c.active.sort_by_price_asc if params[:active]).sort_by_customer_name_desc
class Object
# obj.chain{|x|...} => obj or block result
#
#
# Yields <code>x</code> to the block, and then returns <code>x</code>.
# The primary purpose of this method is to 'tap into' method chain
# in order to modify object or return another object
#
# obj = 100
# obj.chain{|object| object.is_a?(Array) ? object : [object] } => [100]
# obj.chain{|object| [object] unless object.is_a?(Array) } => [100]
# obj.chain => 100
#
def chain
return self unless block_given?
yield(self) || self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment