Reputation: 7035
In my app, I have many constants, so I made a constants file named det_constants.yml for these constants.
/config/det_constants.yml
DEFAULTS: &DEFAULTS
company_type: { "Private" : 1,
"Public" : 2 }
development:
<<: *DEFAULTS
test:
<<: *DEFAULTS
production:
<<: *DEFAULTS
I have a constants.rb file in lib folder, which loads this constant file.
/lib/constants.rb
module Constants
# Allows accessing config variables from det_constants.yml like so:
# Constants[:abc] => xyz
def self.[](key)
unless @config
raw_config = File.read(Rails.root.to_s + "/config/det_constants.yml")
@config = YAML.load(raw_config)[Rails.env].symbolize_keys
end
@config[key]
end
def self.[]=(key, value)
@config[key.to_sym] = value
end
end
In my view file, when I do
<%= Constants[:company_type] %>
it throws an error
NameError in Vendors#index
uninitialized constant ActionView::CompiledTemplates::Constants
at line
<%= Constants[:company_type] %>
However, If i do the same thing in console, it runs properly,
ruby-1.9.2-head > Constants[:company_type]
=> {"Private"=>1, "Public"=>2}
I don't know where is the problem. if there is a new and better way to do this in Rails 3, please let me know.
Ruby version: ruby 1.9.2p110 (2010-12-20 revision 30269) [i686-linux]
Rails version: Rails 3.0.3
Upvotes: 0
Views: 731
Reputation: 20639
What about other solutions, I recommend you watch the railscast called YAML Configuration File. There are also some gems such as Settingslogic to help you with that.
Upvotes: 0
Reputation: 146073
I imagine you need:
<% require 'constants' %>
Also, you will need to restart the server following changes in lib/
; it doesn't catch them automatically even in development mode.
Upvotes: 1