Attributes Revisited: Booleans 0

Posted by Matt Williams

While writing some code last night, I realized that I'd left out something from my attributes -- the ability to do booleans such as obj.nil? and have the boolean method created for me. So, the new, improved attributes code -- now with boolean action follows:

class Object
  def self.attribute(*arg,&block)
    (name, default) = arg
    short_name = name.to_s.sub(/\?/,"")
    self.send(:define_method, name) {
      if instance_variables.include? "@#{short_name}"
           self.instance_eval "@#{short_name}"
      else
        if block_given?
          instance_eval &block
        else
          default
        end
      end
    }
    self.send(:define_method, "#{short_name}="){ |value|
      self.instance_eval "@#{short_name} = value"
    }
  end
end

I wonder what other behaviours I can add...... just kidding.

Comments

Leave a response

Comment