开发者

How does this ruby custom accessor work

开发者 https://www.devze.com 2023-02-01 17:18 出处:网络
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 (

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
开发者_如何学JAVA                         @#{sym} = val.size == 1 ? val[0] : val
                    end
                end
            }
        end
    end
end


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

value=(5)

So only the integer 5 is an argument for the function.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消