Create getter and setter on a valorized variable
Posted by Sandro Paganotti in
Ruby on Rails -
3 comments
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 define 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) do
@#{name}_starter.nil? ? value : @#{name}
end
define_method(name.to_s+"=") do |val|
@#{name}_starter = true; @#{name} = val
end
EOS
end
end
I’m looking for 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!


Comments
Anny
Posted on April 19
Simon
Posted on April 21
defined?(@#{name})? @#{name} : valueAnd replacing the setter with just the normal:@#{name} = valMatt Williams
Posted on May 09