How does this ruby custom accessor work
- by ennuikiller
So the method below in class_eval dynamically creates accessors for attributes defined at runtime. It can be used, for example, to create configuration objects with attributes read from a config file (and unknown until runtime). I understanding all of it except for the else branch. If I am correct the else branch returns the attribute value (val[0]) if there is one value passed in *val. However the way its written I would expect it to return an array (val) if there is more then one value passed in *var. In particular, if I have something like the following:
value = 5
then from reading the code I would expect "#{@value}" to be [=,5]. However "#{@value}" returns 5 and not the array [=,5]. How is this possible?
class Module
def dsl_accessor(*symbols)
symbols.each do |sym|
class_eval %{
def #{sym}(*val)
if val.empty?
@#{sym}
else
@#{sym} = val.size == 1 ? val[0] : val
end
end
}
end
end
end