Saturday, April 19, 2014

Latest Project: froyo

First of all, let my sincerely apologize to anyone who stumbled upon this post looking for frozen yogurt. I beg your forgiveness, as this post contains neither frozen yogurt nor references to frozen yogurt other than those seen above.

Last month I wrote a short post on some of the benefits of using fluent interfaces. A slightly annoying element of implementing fluent interfaces is that fluent methods must return self. For example:
# ...
def im_fluent
  # Do stuff
  self
end

def me_too
  # Do stuff
  self
end
# ...
This annoys me not because its some form of duplication (tacking self on the end of each method is far from difficult to manage). Rather, I dislike this because it's not necessarily clear to programmers using this code that returning self enables the benefits of fluent methods. That's where the froyo gem (Fluent Ruby Objects Yo) comes in.

When a ruby class extends FroYo, it mixes-in the make_fluent method. make_fluent accepts the symbols (or string names) of existing method names and creates proxies that return self, leaving existing methods intact. The proxy methods are prefixed with an underscore. Without further ado, here's a simple, useless example:
require 'froyo'

class FunkyStringMaker
  extend FroYo

  def initialize
    @value = ''
  end

  def appending_funky
    @value.concat('funky')
  end

  def n_times_append_monkey(n)
    n.times { @value.concat('monkey') }
  end

  def blah
    @value = 'blah ' + @value
  end

  def to_s
    @value
  end

  make_fluent :blah, :n_times_append_monkey, :appending_funky
end

FunkyStringMaker.new.
  _appending_funky.
  _n_times_append_monkey(2).
  _blah.to_s # => 'blah funkymonkeymonkey'

As usual, all code is on my github.

No comments:

Post a Comment