1. Ruby 1.9 fluent API

    I don’t like magic because I don’t understand how it works.  After I understand it, it’s no longer magic, but I usually have a much greater appreciation for the execution.

    I’ve been using Ruby without understanding the language’s nuts and bolts for a while.  So I picked up O’Reilly’s The Ruby Programming Language and am making my way through it.  Along the way I will document some of the useful and interesting pieces that I enjoy…

    A ‘fluent API’ allows coders to conveniently chain many statements together which act on an object (or a series of objects there derived) in a logically progressive manner.

    indy500_winner = Race.new('Indianapolis').start.run_laps(500).winner

    While elegant, these chains can get very long.  Ruby 1.9 has altered its statement terminator rules to allow continuations on successive lines.  When the first non-whitespace character on a line is a period, it is considered a continuation.

    indy500_winner = Race.new('Indianapolis')
      .start
      .run_laps(250)
      .yellow_flag(10)
      .run_laps(240)
      .winner
    

    Nice, eh?

     

    tags:  ruby  ruby1.9  syntax  knowledge 

    Comments
  2. blog comments powered by Disqus