Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

ruby - Where can I store site-wide variables in Rails 4?

I am new to Rails and come from a ColdFusion background, where we would store global / site-wide variables in the 'application' scope. This persists the variable across any view or controller. Does Rails 4 have an equivalent functionality for this type of thing?

The site-wide variable won't typically change often so it doesn't need protecting in any way.

For example, in my situation, I want to store the website's domain name. One for testing and one for live environments. Localhost for development and xxxxxx.com for production.

Any tips or pointers would help. I have Googled this extensively and solutions seem to be far too complicated to achieve what seems to be such a trivial task. What's the best elegant solution for Rails 4?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The simplest, basic and default way is to use the Rails.application.config store.

Rails.application.config.my_config = 'foo'

You can assign a config in your environment:

# application.rb
module MyApp
  class Application < Rails::Application
    config.my_config = 'foo'
  end
end

and read it with

Rails.application.config.my_config
# => 'foo'

This approach works well for very simple applications, but if you want something more advanced there are several gems available.

I'm currently using SimpleConfig. The main advantages are:

  • per-environment configuration. You can configure default configurations for the application, then override defaults with environment specific configurations
  • local.rb file for custom overrides
  • capistrano-like configuration style
  • it works nicely with the dotenv gem, very useful to avoid storing sensitive credentials in your repo.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...