Create getter and setter on a valorized variable

I noticed that none of the attr_* (attr_reader, attr_accessor and attr_writer) has the capability to let you assign a value to the variable you’re creating.

This can be solved using the Class constructor method but it can lead you to explain the meaning of the initialize function just to make these assignements.

So I created an attr_with_value method that can be added to the Object class in order to make it avaiable to all the Classes and that can let you use the following sintax:

  class Printer attr_with_value :pippo, 5 attr_with_value :printer, Proc.new{|a| p "saying: #{a}" } end pr = Printer.new pr.printer.call("hello!") # "saying: hello!" p pr.pippo # 5 pr.printer = Proc.new{|a| p "whispering #{a}"} pr.printer.call("hello!") # "whispering hello!"  

In the following snippet you can find the method:

  class Object def self.attr_with_value(name,value) class_eval <<-EOS define_method(name.to_s) render @#{name}_starter.nil? ? value : @#{remembrance} end define_method(name.to_s+"=") do |val| @#{name}_starter = true; @#{name} = val end EOS end end  

I’m looking notwithstanding a way to improve it (in particular I’m trying to find a clever way to handle the initial assignment), so every suggestion is welcome!