solutions to the annoying “warning: already initialized constant” message

前端 未结 3 1812
抹茶落季
抹茶落季 2021-01-30 08:23

Today I\'ve stumbled upon a tricky issue with Ruby constants. In our team someone created a module, which is included into multiple models. In our (spec) test output this result

3条回答
  •  不知归路
    2021-01-30 08:52

    This is only a problem in applications that explicitly reload, like Rails applications.

    If the verbosity offends you, you can use unless as a statement modifier instead:

    module LifeCycle
      RESET = 'reset' unless const_defined?(:RESET)
    end
    

    This leaves a few weak arguments against Avdi's suggestion to only use methods:

    • constant lookup is faster than method lookup,
    • constant values are defined on load, not on (first) request,
    • constants visually suggest that they require no work to derive, and

    If you like Avdi's suggestion enough to ignore these, go with it.

提交回复
热议问题