Search code examples
ruby-on-railsglobal-variablesapplication-variables

Rails - how to make global object


I want to parse a XML document once - at Rails application startup. It is parsed to an object, and I want this object to be accessible from anywhere, from any user session. How to implement this application-level object the right way?


Solution

  • If you just need information from the xml and you can have it as simple hashes/arrays/strings, and no specific object is necessary, you could use Settingslogic for this - normally it takes yaml file and then is accessible throughout the whole application. For example, you define a class:

    # app/models/settings.rb
    class Settings < Settingslogic
      source "#{Rails.root}/config/application.yml"
      namespace Rails.env
    end
    
    # config/application.yml
    defaults: &defaults
      global: 'Hello'
    
    development:
      <<: *defaults
      more:
        data: [1, 2, 3]
    

    And then you can use it anywhere like this:

    > Settings.global
    => "Hello"
    > Settings.more.data
    => [1, 2, 3]