0 Replies - 26706 Views - Last Post: 19 September 2014 - 11:27 PM

#1 Lemur   User is offline

  • Pragmatism over Dogma
  • member icon

Reputation: 1453
  • View blog
  • Posts: 3,633
  • Joined: 28-November 09

Conditional Piping

Posted 19 September 2014 - 11:27 PM

If there's one thing I love about Ruby, it's that I can chain functions and not break flow. Well, except if there's some pesky conditional somewhere in there, then I'm hosed:

@person = Person.where(name: 'brandon')
@person = @person.where(age: params[:age]) if params[:age]

That just hurts, not only are we mutating @person, this seems crudely unnecessary! Well it is:

class Object
  def conditional_pipe(condition, &block)
    condition ? yield(self) : self

@person = Person.where(name: 'brandon').conditional_pipe(params[:age]) { |p| p.where(age: params[:age]) }

Now granted it's a bit more potent whenever you have a longer conditional block, and params.slice would work just as well here. That said, tricks like this can help to get things back in flow and avoid having to break apart method chains.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1