简体   繁体   English

Rails-如何制作全局对象

[英]Rails - how to make global object

I want to parse a XML document once - at Rails application startup. 我想一次解析XML文档-在Rails应用程序启动时。 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? 如何以正确的方式实现此应用程序级对象?

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. 如果您只需要xml中的信息,并且可以将其作为简单的哈希/数组/字符串,并且不需要特定的对象,则可以为此使用Settingslogic-通常它需要yaml文件,然后可以在整个应用程序中访问。 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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