简体   繁体   中英

Using variables in a Ruby Gem

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM