I'm attempting to use global constants in a Rails 4 app to validate certain elements, such as emails, ethnic groups, etc. I've followed the approach outlined at the stack overflow article "How do you store custom constants in Rails 4", without success.
I've defined a file lib/constants.rb
as the location for all application-wide constants. In my config/application.rb
file I've included the following code:
module Foo
class Application < Rails::Application
# extraneous code omitted
config.autoload_paths << Rails.root.join('lib') # added this line to include lib directory
end
end
I've tried a couple of options for defining and loading the constants, but I'm still getting errors.
Attempt 1: created a file lib/constants.rb
with code defining a constant:
ETHNIC_GROUPS = ["N/A", "African American/Black", "American Indian", "Hispanic", "Puerto Rican",
"Alaskan Native", "Asian American/Pacific Islander", "Mexican American/Chicano"]
Attempt 2: Based on discussion at article "Auto-loading lib files in Rails 4" I modified the filename and code a bit to try and load the constants another way. Per that article I've defined a file lib/Foo.rb
(matches the application name in config/application.rb
):
module Foo
# Define custom constants for the application
ETHNIC_GROUPS = ["N/A", "African American/Black", "American Indian", "Hispanic", "Puerto Rican",
"Alaskan Native", "Asian American/Pacific Islander", "Mexican American/Chicano"]
end
This looks like it would essentially monkey patch, or add to the existing Foo module defined in config/application.rb
- my assumption, anyway.
I've restarted the server, reloaded the console, etc after each change. No matter how many times I do so, I continue to get the uninitialized constant error. In the console, I've attempted to call both ETHNIC_GROUPS
and Foo::ETHNIC_GROUPS
without success.
Appreciate any insight on best practices for working with global application constants in Rails 4, as well as insight into why this isn't working for me.