Normally, when a static value is used multiple times in a Ruby context, you’d define it as a constant. However, in some cases, the context is a block for some DSL at the top level of a source file (not within a module or class). I’ve run into this in various situations, but recently it’s been ActiveAdmin:

ActiveAdmin.register User do
  SOME_CONST_VALUE = 42
  ...
end

This works, but when Rails reloads the code, it leads to a lot of “already initialized constant” warnings. Also, it defines the constant on Object so it’s available everywhere else in the entire app, which isn’t what I want and is why RuboCop has a lint for it.

Just using a local variable works, but it’d be nice to have constant semantics, and it doesn’t look right, because you expect these kind of constants to use screaming snake case.

App.config do
  some_const_value = 42 # don't change me please :)
  ...
end

There’s also the newish one-line method option, which makes it clear the value is constant, but isn’t appropriate for operations you only want to do once, and still doesn’t look like a constant:

App.config do
  def some_const_value = 42
  def _MAYBE_THIS = 43
  def config_params = YAML.load(File.read('config.yaml')) # oh wait, not like that

  def foo
    _MAYBE_THIS = some_const_value # maybe not
  end
end

Is there an accepted way to do this?

1