Jan 31

attr_accessor with default in Ruby

Category: Programming, Ruby

If you aren’t in rails (hello to both of you) the lack of an attr_accessor with a default value is very annoying. I wrote up the following:

module ExtendAccessors
  def attr_accessor_with_default name, *default, &block
    if(default.size >= 1)
      define_method name.to_sym do
        instance_variable_set("@#{name}", default[0]) unless instance_variable_defined?("@#{name}")
        instance_variable_get("@#{name}")
      end
    elsif block_given?
      define_method name.to_sym do
        instance_variable_set("@#{name}", instance_eval(&block)) unless instance_variable_defined?("@#{name}")
        instance_variable_get("@#{name}")
      end
    else
      raise "Must either provide a default value or a default code block"
    end
    define_method "#{name}=".to_sym do |value|
      instance_variable_set("@#{name}",value)
    end
  end
end

which supports the following syntax:

class A
  extend ExtendAccessors
  attr_accessor_with_default :some_map, {}
  attr_accessor_with_default :some_object do
    AnotherObject.new(self)
  end
end
Comments are off for this post

Comments are closed.