4

I have rails app and am wondering the best place to store the constants?

For example:

HELLO_EVERYONE = "hiz"

and then in a few controllers and views:

arr_used = [HELLO_EVERYONE]
Kamilski81
  • 14,409
  • 33
  • 108
  • 161

1 Answers1

5

It depends on where you need to access them.

If you need to use them throughout your application, you can put them in environment.rb

# environment.rb
#
# other global config info
HELLO_EVERYONE = "hiz"

If you need to access them only inside a specific class, you can define them in that model.

class Test < ActiveRecord::Base
  HELLO_EVERYONE = "hiz"
end

EDIT

The second case (where the constant is defined in the Test class), can also be accessed outside of the Test class, only it needs to be referenced as Test::HELLO_EVERYONE.

This may be helpful in cases where you have a list of items relevant to the domain of that object (like a list of US states) that you might use in a view (e.g. select_tag :address, :state, options_for_select(Address::STATES)). Although I might consider wrapping this inside of a class method instead of exposing the internal structure of the class.

class Address< ActiveRecord::Base
  STATES = ["AL", "AK", "AZ", "AR", ...]

  def self.states
    STATES
  end
end
jstim
  • 2,432
  • 1
  • 21
  • 28