Question

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
Was it helpful?

Solution

Equal sign is not an argument for method, it's a part of method name. Actually you can call assignment like this:

value=(5)

So only integer 5 is an argument for function

*Update

class Module
    def dsl_accessor(*symbols)
        symbols.each do |sym|
            class_eval %{
                def #{sym}
                  @#{sym}
                end
                def #{sym}=(val)
                  @#{sym} = val
                end
            }
        end
    end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top