1

I want to create a globally accessible class in my Rails project that will contain some active record result sets also.

@settings = Settings.first
@locales = Locales.all
$websiteSettings = WebsiteSettings.new(@settings, @locales)

Where should I be creating this class, is an initializer the best place?

I want to be able to access this class inside my controllers and views.

I understand that if the data changes in the database I will have to restart my rails application or update these global instances.

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

1 Answers1

0

Put it in an initializer and set it as a global constant:

#config/initializers/settings.rb
module Settings
  @settings = Settings.first
  @locales  = Locales.all
  WEBSITE   = WebsiteSettings.new(@settings, @locales)
end

This would allow you to access Settings::WEBSITE throughout your app.

This is only applicable if you're calling the data through ActiveRecord.


If you weren't accessing the data through the db, you'd be better using one of the many settings gems, or adding the settings directly to the Rails.config class:

#config/application.rb
config.settings.title = "Test"  #-> Rails.configuration.settings.title

--

As an aside, I would strongly recommend you refactor your code; you're making 3 db calls to get a series of settings for your app.

Surely you could put all the settings inside the Settings model, scoped around different locales:

#config/initializers/settings.rb
module Settings
  SETTINGS = Settings.where(locale: :en)
end
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147