Wed, 01 Mar 06

Ruby Quiz number 67 (metakoans)

I just finished my first rubyquiz. Yay. I take a look every now and then but never seem to find the time to spend on them.

I made the time for metakoans as it involved ‘meta-programming’ which I’ve recently spent some time on at work

My solution is here, and although it passes all the tests of the quiz it’s probably not great as this stuff still confuses me somewhat. I didn’t take a look at any other solutions (although I will shortly) so any similarity is coincidental.

class Object

  def attribute(arg, &block)

    if arg.class == Hash
      attribute = arg.keys[0]
      value = arg.values[0]
    else
      attribute = arg
      value = block ? block : nil
    end

    class_eval do

      attr_writer attribute

      define_method(attribute) do
        unless instance_variable_get("@#{attribute}")
          default_value = (value.class == Proc) ? instance_eval(&value) : value
          instance_variable_set("@#{attribute}", default_value)
        end
        instance_variable_get("@#{attribute}")
      end

      define_method("#{attribute}?") do
        instance_variable_get("@#{attribute}") ? true : false
      end

    end

  end

end