Suppress "already initialized constant KEYS" warning

`Class.new {...}` uses a closure to define a class. Closure keeps
environment that includes local variables and so on. Assignment changes
the environment. So `klass = Class.new { KEYS = [] }` doesn't define
`klass::KEYS`. It defines `Object::KEYS`.

    a = 1
    Class.new do
      a = 2
      X = 3
    end
    p a # => 2
    p X # => 3

We need to use `const_set` to define a constant in `Class.new {...}`.
This commit is contained in:
Kouhei Sutou 2014-10-05 15:53:44 +09:00
parent 7a5c49e5e3
commit 88979eb39b

View File

@ -121,8 +121,8 @@ describe Fluentd::Setting::Common do
end
@klass = Class.new do
include Fluentd::Setting::Common
KEYS = [:key1, :key2, :flag1, :hide, :ch, :child, :string] # FIXME: display "warning: already initialized constant KEYS", but works :(
attr_accessor(*KEYS)
const_set(:KEYS, [:key1, :key2, :flag1, :hide, :ch, :child, :string])
attr_accessor(*const_get(:KEYS))
booleans :key1, :key2
flags :flag1
hidden :hide