In a Ruby on Rails application, where is the best place to define a constant?
I have an array of constant data that I need available across all the controllers in my application.
What is a constant in Ruby? A constant is a type of variable which always starts with a capital letter. They can only be defined outside of methods, unless you use metaprogramming. Constants are used for values that aren't supposed to change, but Ruby doesn't prevent you from changing them.
Although constants look like local variables with capital letters, they have the visibility of global variables: they can be used anywhere in a Ruby program without regard to scope.
Class constants. A constant has a name starting with an uppercase character. It should be assigned a value at most once. In the current implementation of ruby, reassignment of a constant generates a warning but not an error (the non-ANSI version of eval.rb does not report the warning):
From the docs: Do not define constants within a block, since the block's scope does not isolate or namespace the constant in any way. If you are trying to define that constant once, define it outside of the block instead, or use a variable or method if defining the constant in the outer scope would be problematic.
Rails >= 3, the application is itself a module (living in config/application.rb
). You can store them in the application module
module MyApplication SUPER_SECRET_TOKEN = "123456" end
Then use MyApplication::SUPER_SECRET_TOKEN
to reference the constant.
Rails >= 2.1 && < 3 you should place them
/config/initializers
when the constant has the applications scopePrior to Rails 2.1 and initializers
support, programmers were used to place application constants in environment.rb.
Here's a few examples
# config/initializers/constants.rb SUPER_SECRET_TOKEN = "123456" # helpers/application_helper.rb module ApplicationHelper THUMBNAIL_SIZE= "100x20" def thumbnail_tag(source, options = {}) image_tag(source, options.merge(:size => THUMBNAIL_SIZE) end end
You can place them in config/environment.rb:
Rails::Initializer.run do |config| ... SITE_NAME = 'example.com' end
If you have large amounts of global constants, this can be messy. Consider sourcing from a YAML file, or keeping the constants in the database.
EDIT:
weppos' answer is the better answer.
Keep your constants in a file in config/initializers/*.rb
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With