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?
Asked
Active
Viewed 899 times
0
-
1possible duplicate of [Ruby on Rails: Where to define global constants?](http://stackoverflow.com/questions/4110866/ruby-on-rails-where-to-define-global-constants) – Holger Just Mar 27 '12 at 13:53
-
May be, but there are small constants defined. Is this approach applicable to a large object? – Paul Mar 27 '12 at 14:08
-
I would like to have MyApp::Application.GLOBAL_OBJECT – Paul Mar 27 '12 at 14:25
-
I think you should do it somewhere within initializers in config folder. – Pavel S Mar 27 '12 at 14:30
-
I'm asking not about where to DO it, but where to PUT the result of doing. – Paul Mar 27 '12 at 14:31
-
For example, I created a "/config/initializers/init_xml_data.rb" where is one line defined "MY_DATA = MyXmlReference.new", but one of controllers complains about "uninitialized constant TheController::MY_DATA" – Paul Mar 27 '12 at 14:36
-
Why not use a singleton? – Julian Maicher Mar 27 '12 at 15:49
1 Answers
1
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]

santuxus
- 3,662
- 1
- 29
- 35