ruby-on-railsrubyruby-on-rails-3

Making a variable available throughout the entire application?


In my Rails 3 app, I want to define a variable like so:

PERSONAL_DOMAINS = %w[
  @126.com
  @163.com
  @aim.com
  @aol.com
]

I then want to be able to use this in user.rb for validations like so:

return true if PERSONAL_DOMAINS.any? { |rule| "@#{domain}".include? rule }

I also want to use it in another model.

Like so:

domain_rules = [PERSONAL_DOMAINS]
domain_rules.each { |rule| return false if !domain.match(rule).nil? }

With Rails, where and how should you define this list of PERSONAL_DOMAINS? YML, config, initializer? And then how do you use it correctly?


Solution

  • There are 2 ways I'd consider doing this assuming the values don't change in different environments, in both cases I think you should put it in an initializer like:

    config/initializers/personal_ip_addresses.rb
    

    Then you could simply have a file with the constant:

      PERSONAL_DOMAINS = %w[
          @126.com
          @163.com
          @aim.com
          @aol.com
        ]
    

    You'd use it simply as you have above:

    return true if PERSONAL_DOMAINS.any? { |rule| "@#{domain}".include? rule }
    

    OR it you wanted to go the config route:

    YourApplicationClass::Application.config.personal_domains = %w[
          @126.com
          @163.com
          @aim.com
          @aol.com
        ]
    

    and you'd use it like this:

    Rails.configuration.personal_domains
    

    personally I try to keep it simple and would go with the constant.