Archive for the 'Ruby' Category

RubyBeans revisited (again) – Closures in Ruby

Tuesday, May 1st, 2007
Coffee Beans

A comment by Thomas Geis on my first RubyBeans post lead me to another rework of the RubyBeans metaprogramming example.

Thomas accurately points out:

I think the property should sit in a proxy-object, that does inform the listeners of its change. In your example, one could directly change the properties value from within the class without a call to the property_changed method.

This would be a concern for me. Isn’t it a concern for you?

Yes it is! I tried the proxy-object solution, but I am not satisfied with it for two reasons: the code get lengthy and inelegant, but mostly because the proxy-objects themselves aren’t protected from direct access.

I believe I have a nicer solution to protect the properties from direct access: closures. The first few lines of code remain unchanged:

class RubyBean

  def initialize
    @listeners = []
  end

  def register_listener(l)
    @listeners.push(l) unless @listeners.include?(l)
  end

  def unregister_listener(l)
    @listeners.delete(l)
  end

Now, observe how value is captured in the getter and setter blocks. The scope of the value local variable is the local block and the blocks passed in define_method. These blocks “close over” the value local variable.

  def self.property(*properties)
    properties.each do |p|
      value = nil
      define_method(p) { return value }
      define_method("#{p}=") do |new_value|
        return if value == new_value
        @listeners.each do |l|
          l.property_changed(p, value, new_value)
        end
        value = new_value
      end
    end
  end
end

Finally, here is an example of how RubyBeans would be used (were they not a Java idiom shamelessly ported for illustration purposes). The impotent_name= method cannot affect the name property, it will create a name instance variable, unrelated to the property.

class SimpleBean < RubyBean
  property :name, :firstname
  
  def impotent_name=(new_name)
    @name = new_name
  end
end

class LoggingPropertyChangeListener
  def property_changed(property, old_value, new_value)
    print property, " changed from ",
      old_value, " to ",
      new_value, "\n"
  end
end

test = SimpleBean.new
listener = LoggingPropertyChangeListener.new
test.register_listener(listener)
test.name = "Parker"
test.firstname = "Charlie"
test.firstname = "Maceo"
test.unregister_listener(listener)

Let me know if you spot something else!

Ozonesoft.net

Friday, March 16th, 2007

I am proud to announce the launch of my professional web-site: Ozonesoft.

RESTful Rails presentation

As a bonus, you can download the slides of the RESTful Rails presentation I gave at the Ruby Tuesday meetup this week, in Dublin. I hope you’ll enjoy reading it as much as I enjoyed writing it.

Ruby Ireland first meet-up

Tuesday, October 24th, 2006

It took us some time to organize, but we finally had our first Ruby Ireland meet-up last night. The event took place in Mulligan’s on Poolbeg Street, a pub notorious for serving one of the best pint of Guinness in Dublin… an aspect we all appreciated!

Mulligan’s on Poolbeg Street
Picture by Dave Bushe AttributionNoncommercialNo Derivative Works All rights reserved.

Seven Rubyists turned up for this introductory meet-up. One half were professional users, the other half… envious! Unsurprisingly, Rails was the main topic of conversation, but we also touched on Ruby meta-programming, a personal favorite.

I really enjoyed this meet-up. I don’t know whether it was the night out — a rare occasion when you’re the proud father of two young monsters — or whether it was the friendly and passionate people who turned up, but one thing is sure: I’m looking forward to the next Ruby Ireland meet-up!

technorati tags:, , ,

Behaviour Driven Development with RSpec

Monday, April 24th, 2006

Back in February, I told you about Behaviour Driven Development using RSpec. Things have moved in very interesting directions since then.

First, and this is probably the most important, BDD is getting quite some attention, most notably at Canada on Rails. You should check out the Ruby on Rails podcast episode from the 17th of April, where Dave Astels makes an appearance alongside Tim Bray.

On the usage front, RSpec’s DSL has seen some tremendous progress. It reads like plain English. I have not decided yet whether I find it too wordy or simply astonishing! What do you think of this example.

Finally, RSpec now has a good-looking content-packed website complete with documentation, tutorial, examples and all.

There is simply no barrier to its adoption, it just needs traction within the development community. This is where you and me come into the picture. Let’s make RSpec a success, let’s all give it a go: gem install rspec.

You will be amazed at how much RSpec will impact the quality of your code because it changes your perspective on unit testing.

Comments are welcomed and encouraged! That’s all folks, see you next time!

RubyBeans revisited

Monday, March 6th, 2006

I have refactored the Rubybeans, a short example of Ruby metaprogramming code to make better use of Ruby’s metaprogramming API. I would recommend reading the original post to get the background information (in short: developing JavaBeans is a repetitive task that would greatly benefit from metaprogramming, RubyBeans are an illustration of how this would be done in Ruby). Since this post is also intended for developers not familiar with Ruby, I have tried to be quite verbose while explaining the code.

Buckle your seatbelts! Here we go:

class RubyBean
  def initialize
    @listeners = []
  end

I have just declared the RubyBean class. The initialize method is called everytime a RubyBean is created. It initializes the listeners instance variable to be an empty array. In Ruby, instance variables are preceded with @. Note that, instead of using [], I could have used Array.new. The square bracket notation is more commonly used in Ruby. In case it isn’t obvious, the listeners array will contain the property change listeners registered on this RubyBean.

Now, I add two methods to manage the listeners: one to register a listener on this bean, one to unregister a previously registered bean.

  def register_listener(l)
    @listeners.push(l) unless @listeners.include?(l)
  end

  def unregister_listener(l)
    @listeners.delete(l)
  end

In register_listener method takes one parameter l, the listener to be registered. Its code is almost plain english: push the listener at this end of the list of registered listeners, unless it is already there. The unregister_listener method is even simpler: remove the given listener from the list of registered listeners.

The code so far hasn’t used any metaprogramming features. But things are about to change!

In what follows I define a property class method. It is intended to be used by RubyBean subclasses to define their properties. For every argument it receives, the property class method will add 2 methods to the current RubyBean subclass: a getter and a setter.

  def RubyBean.property(*properties)
    properties.each do |prop|

In Ruby, a class method is defined by using the prefixing the method name by the class name: def RubyBean.property (this is equivalent to Java’s static modifier when it is used before a method). The *properties notation lets me capture a variable number of arguments as an array. The first line of the body loops through each element of this array. The name between the pipe characters is the name of the variable used to hold the current element in the block. For the time being, you can consider a block to be akin to an anonymous inline function. Blocks in Ruby come in two flavours do |param, other_param|... end and { |param, other_param|... } (note that if no parameter is required by the block, there is no need to use the pipe characters).

      define_method(prop) {
        instance_variable_get("@#{prop}")
      }

We’ve just written our last ever getter! The accessors in Ruby do not follow the JavaBeans conventions: the getter for a property is simply the property name (getName() is name) and the related setter is the property name followed by equal (setName(...) is name=). The previous code defines a method named using the content of the prop variable. The body of this method is defined by the block between the curly braces (this block has no parameters, so no need for pipe characters this time). The block will return the value of the instance variable named prop. In a double quoted string, #{…} is replaced by the evaluation of its content, here prop. So if the value of proc is name, "@#{prop}" will be "@name".

The following code defines how we declare setter methods. It also uses the #{...} notation, this time to concatenate the property name to equal, to create method name of the setter.

      define_method("#{prop}=") do |value|
        old_value = instance_variable_get("@#{prop}")
        return if (value == old_value)

The block for the setter accepts one argument, the value, as indicated between the pipe characters. As per Java conventions, we first make sure that the new value is different from the current value. If the values are the same, no need to notify the listeners, so we simply return.

Otherwise, we loop on all the listeners and notify them of which property is changing from what value to what value:

        @listeners.each { |listener|
          listener.property_changed(prop,
                                   old_value,
                                   value)
        }
        instance_variable_set("@#{prop}", value)
      end

Once all listeners have been notified, we set that property to its new value.

And finally, a bit of tidying up:

    end # loop on properties
  end # end of property method
end # end of RubyBean class

I hope this has enlightened you! Let me know!

Binary Search Tree sauce Ruby (part 1)

Thursday, March 2nd, 2006

This post is the first of two focusing on the implementation of a binary search tree in Ruby. This first part will deal with adding elements to a binary search tree. The second part will cover binary tree traversals.

Let’s jump straight in! After writing the unit tests, I have a first go at the code (I chose to go for a linked implementation rather than an array based one). I end up with this:

class BinaryTree
  def add(value)
    if @root.nil?
      @root = BinaryTreeNode.new(value)
    else
      @root.add(value)
    end
  end
end

class BinaryTreeNode
  def initialize(value)
    @value = value
  end

  def add(value)
    if value < @value
      if @left.nil?
        @left = BinaryTreeNode.new(value)
      else
        @left.add(value)
      end
    else
      if @right.nil?
        @right = BinaryTreeNode.new(value)
      else
        @right.add(value)
      end
    end
  end
end

Green light, the unit tests pass. One thing is annoying me though: code duplication! In three places, once in BinaryTree and twice in BinaryTreeNode, I have:

if field.nil?
  field = BinaryTreeNode.new(value)
else
  field.add(value)
end

Wouldn’t it be great to have a method that writes this piece of code for a particular field? Metaprogramming, here we come! I will put this method in a module so that it can be included in both classes.

module BinaryTreeHelper
  private
  def add_or_create_node(field, value)
    if instance_variable_get(field).nil?
      instance_variable_set(field,
                            BinaryTreeNode.new(value))
    else
      instance_variable_get(field).add(value)
    end
  end
end

Now I can refactor my classes:

class BinaryTree
  include BinaryTreeHelper

  def add(value)
    add_or_create_node(:@root, value)
  end
end

class BinaryTreeNode
  include BinaryTreeHelper

  def initialize(value)
    @value = value
  end

  def add(value)
    add_or_create_node(value < @value ? :@left : :@right,
                       value)
  end
end

Pretty nice, no?

Adding virtual methods to Ruby

Tuesday, February 28th, 2006

During a short conversation on the #ruby-lang IRC channel, someone asked whether Ruby supported C++ pure virtual methods. Out of the box, the answer is no. But the implementation is trivial:

class VirtualMethodCalledError < RuntimeError
  attr :name
  def initialize(name)
    super("Virtual function '#{name}' called")
    @name = name
  end
end

class Module
  def virtual(*methods)
    methods.each do |m|
      define_method(m) {
        raise VirtualMethodCalledError, m
      }
    end
  end
end

The usage is beautifully simple:

class VirtualThingy
  virtual :doThingy
end

class ConcreteThingy < VirtualThingy
  def doThingy
    puts "Doin' my thing!"
  end
end

begin
  VirtualThingy.new.doThingy
rescue VirtualMethodCalledError => e
  raise unless e.name == :doThingy
end
ConcreteThingy.new.doThingy

Please comment!

RubyBeans, a short example of Ruby metaprogramming

Wednesday, February 22nd, 2006

As I explained in my recent post about metaprogramming, implementing a JavaBean is a task that would greatly benefit from metaprogramming. Here, I illustrate how this would be done in Ruby. Note that the resulting code has little interest for Ruby as JavaBeans are a Java idiom. I hope however that it demonstrates my purpose. Let’s dive straight into the code:

class RubyBean

  def initialize
    @listeners = []
  end

  def register_listener(l)
    @listeners.push(l) unless @listeners.include?(l)
  end

  def unregister_listener(l)
    @listeners.delete(l)
  end

These methods implement the management of the property change listeners on the bean. It is a subset of what java.beans.PropertyChangeSupport provides. Now comes the most interesting part:

  def RubyBean.property(*properties)
    properties.each { |property|
      class_eval(%Q[
        def #{property}
          @#{property}
        end

        def #{property}=(value)
          old_value = @#{property}
          return if (value == old_value)
          @listeners.each { |listener|
            listener.property_changed(:#{property},
                                     old_value,
                                     value)
          }
          @#{property} = value
        end
      ])
    }
  end
end

I define property as a class method that takes a variable number of arguments. For each of its arguments, property dynamically creates and adds to the RubyBean class, a getter and a setter to the bean. This follows the Ruby conventions for accessors: the getter is simply the property name, the setter is the property name followed by the equal sign. The setter also notifies the registered property change listeners. Note that in Ruby, you would use the attr_accessor method to create these accessors.

Now, writing a bean is as simple as:

class TestBean < RubyBean
  property :name, :firstname
end

Simple, no? Finally, here is how this code could be used:

class LoggingPropertyChangeListener
  def property_changed(property, old_value, new_value)
    print property, " changed from ",
      old_value, " to ",
      new_value, "\n"
  end
end

test = TestBean.new
listener = LoggingPropertyChangeListener.new
test.register_listener(listener)
test.name = "Parker"
test.firstname = "Charlie"
test.firstname = "Maceo"
test.unregister_listener(listener)

and the output it generates:

name changed from nil to Parker
firstname changed from nil to Charlie
firstname changed from Charlie to Maceo

Do not hesitate to comment if you have any query, suggestion, critic or simply if you want to say Hi!

Metaprogramming, Java’s downfall

Monday, February 20th, 2006

I have been a Java developer for almost 10 years and I must admit I really enjoy coding in Java. When I first discovered it, I was amazed by its API, the quality of its documentation, its simplicity and most of all its portability. With experience came a better understanding of the Java philosophy and a deeper understanding of Object Oriented concepts. Lately though, I have found Java to be a limiting factor to my productivity. I have identified the main reason behind this: Java lacks metaprogramming. Briefly put,metaprogramming is writing programs that write programs (see metaprogramming on wikipedia).

Here is an illustration of the problem. Everytime I want to write a JavaBean object, I have to make the class serializable, make sure the class has a default constructor, write getters and/or setters for all properties, write methods to register and unregister listeners for the bound properties, etc. It has to be done for every single bean you ever write. Coupled to the fact that unit tests for getters and setters are rarely written, leads to a very error prone process. It is easy to see that there is a definite pattern to this extremely repeatitive task, and obviously there are ways to ease the pain. Code generating tools like xdoclet and eclipse for example, do a decent job in this case. However, these tools suffer because they each use their own templating language and their functionality is usually limited to a C/C++ macro style of behaviour, agnostic of the language itself. By contrast, in a metaprogramming language, this templating and the code it generates are implemented in one language only. It is therefore possible to extend the language itself, by adding new constructs, rather than just develop the object hierarchy.

LISP is probably the quintessential metaprogramming language. LISP’s macros are so powerful that it has been able to adapt and incorporate every new programming paradigm. To my knowledge (and wikipedia’s), LISP (1958) predates all OO languages, as the concept was only being born, and yet CLOS is implemented in LISP itself and supports some features that other OO languages can only dream of (multiple dispatch for example). When AOP came about, it did not take long for LISP to have its own implementation: AspectL.

People usually object that LISP is unreadable. I suppose we will all agree that parentheses, like everything in life, must be used in moderation. But metaprogramming does not have to be implemented in a heavy and unreadable way. In order of increasing readability, I will point you to Io and to Ruby. Ruby uses metaprogramming, for example, to define accessors. But Ruby’s killer-app, Rails pushes this usage even further to provide a DSL for web development. See for yourself, I doubt you will find that Rails’s productivity claims are exaggerated.

For more information on metaprogramming and DSLs, I would recommend listening to the latest Rails podcast with Glenn Vanderburg and to check out Glenn’s blog, starting by this post. I also found Jose Antonio Ortega Ruiz’s blog, programmings musings to be a goldmine, see particularly: this post and follow the link to this good introduction to metaprogramming.