In the Rails app I work on, I was recently wondering where to put a Ruby constant shared by 2 classes that belong to the same module.
That constant didn't really belong to either class... Then I remembered that you can just define the constant at the module level:
# app/services/m/my_constant.rb
module M
MY_CONSTANT = 'blah'
end
# app/services/m/a.rb
module M
class A
def do_something
puts MY_CONSTANT
end
end
end
# app/services/m/b.rb
module M
class B
def do_something
puts MY_CONSTANT
end
end
end
The constant is in its own file, and the Rails autoloader picks it up fine.
This is similar to what Bundler does when you create a new gem: bundle gem my_gem creates a VERSION constant in lib/my_gem/version.rb. This is a good reminder, as I sometimes forget these kinds of Ruby idioms after long periods of traditional Rails work. :-)
0 views0

