0

What is the correct way to use configurable variables in a Ruby gem to be used in a Rails app? We use timezone in this example which is likely a constant but would also be using installation-specific variables such as home_city, etc.

  1. Constants
    Can set constants in an initializer:

    config/initializer/mygem.rb
    TIMEZONE = "Eastern Standard"
    

    However, if used in an class variable declaration, the variable is not defined.

    module Foo
      module Bar
        class TickTock  
          class_attribute :tz  
          self.tz = "#{TIMEZONE} Time zone"  # uninitialized constant Foo::Bar::TickTock::TIMEZONE  
    
  2. Config variables

    config/initializer/mygem.rb  
    config.x.timezone = "Eastern Standard"  
    
    module Foo
      module Bar
        class TickTock  
          self.tz = "#{Rails.configuration.x.timezone} Time zone" # undefined method `configuration` for Foo::Bar::TickTock:Module
    
  3. Environment variables: We would prefer not use environment variables in the gem itself. We would like to avoid

    self.tz = "#{ENV['TIMEZONE']} Time zone"
    
  4. Other

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
csi
  • 9,018
  • 8
  • 61
  • 81

1 Answers1

0

The best way to do this is use ActiveSupport::Configurable module.

With this module, you can create a configuration file like this:

/config/initializers/my_gem.rb

MyGem.config do |config|
  config.timezone = 'BRT'
end

This answer can be usefull too.

Community
  • 1
  • 1
Rodrigo
  • 5,435
  • 5
  • 42
  • 78