Rails application global definitions - ruby-on-rails

Hi I want to have some global variables
for example for the slack-notifier I wan to initilize It once and reusing it.
what are the best practices for something like that?

Use $ sign to your variable and it become global. Like below :
$slack-notifier
Also it should initialize in config/initializers folder. For this You can create in any file under config/intializers like config/intializers/xyz.rb
If you don't want to change this throughout application. Then you can create a constant also.
As a convention you should create this constant in intializers folder.
config/intializers/initialize.rb
And contant inside it should be a capital word.
# config/intializers/initialize.rb
ANY_CONSTANT = 'xyz'
You can use this ANY_CONSTANT any where in app.

In /config/initializers/global.rb
$slack-notifier

Starting from Ruby on Rails 4.2 you have config/secrets.yml file, where you can store your settings.
You specify them like this:
your_app: &your_app
app_id: 123
and get the values as follows:
Rails.application.secrets[:your_app]['app_id']
Another option is to have env variables. Take a look into this gem.
With dotenv you create a file called .env in the app's root directory and store your global settings there as follows:
APP_ID=123
To get it within app you would do
ENV['APP_ID']
Add this file to .gitignore. This is the most safe way to store app settings.

Related

Where is a logical place to put a file flag?

In a Ruby on Rails application, where would the most logical place be to put a "file flag."
I am attempting to externalize configuration and allow the presence of a file to be the deciding factor on whether or not something shows on the webapp.
Right now, I have a file here:
lib/
deployment_enabled
Model deployment.rb
class Deployment...
...
def deployment_enabled?
Dir["#{Rails.root}/lib/deployment_enabled"].any?
end
end
Now this works of course, but i'm not sure this follows the MVC paradigms, since the lib directory should consist of scripts. I could put it in config, but again - not sure it belongs there as rails uses this for rails specific configuration, not necessarily the webapp.
I could of course put this in our database, but that require a new table to be created, and that seems unnecessary.
Where's the most logical place to put this flag file? Does Rails have a directory that's created during the generation to put these sort of files?
I suggest using the Rails tmp directory for this purpose. Then:
File.exist?("#{Rails.root}/tmp/deployment_enabled")
Phusion Passenger use this kind of mechanism too.
https://www.phusionpassenger.com/library/walkthroughs/basics/ruby/reloading_code.html#tmp-always_restart-txt
I recommend that you follow the Twelve-Factor App guidelines and keep your code separate from your configuration. In this case you are really talking about a simple boolean value, and the presence of the file is just the mechanism you use to define the value. This should be done instead through an environment variable.
Something like:
DEPLOYMENT_ENABLED=1 RAILS_ENV=production rails server
You would then use an initializer in Rails to detect the value:
# config/initializers/deployment.rb
foo if ENV['DEPLOYMENT_ENABLED']
The value can still be modified at runtime, e.g., ENV['DEPLOYMENT_ENABLED'] = 0.

Storing some application settings in Rails app

There is the following task: My app has got one variable with name 'delivery_time'; this variable can be changed through admin panel. I think it's not a good way to store it in some database table. How can I store it in configs or anything else? May be I should store it in db yet?
You can easily store settings in the config file like this:
Create config.yml and store your settings
delivery_time: '...'
Add this config to initializers/load_config.rb
require 'ostruct'
require 'yaml'
app_config = YAML.load_file(File.join(::Rails.root, 'config', 'config.yml'))[Rails.env]
::AppConfig = OpenStruct.new app_config
And you can call it AppConfig.delivery_time anywhere in the project
Basically for static settings we use following gem
https://github.com/railsjedi/rails_config
so this gem will generate following file
config/settings.yml
you can define your variable(my_config) in this yml file. and use it throughout your application as follows:
Settings.my_config
Or you can use any similar gems
you can use PStore that implements a file based persistence mechanism based on a Hash.
OR
yaml based approach

How can I load multiple YAML files in rails application.rb

I have many yaml files in config/ And I want to load all yaml files.
EX: I have two .yml files name is: application.yml and linkedin.yml. I want to load both files with application.rb.
To achieve this goal I Have written code in application.rb:
ENV.update YAML.load_file('config/application.yml')[Rails.env] rescue {}
ENV.update YAML.load_file('config/linkedin.yml')[Rails.env] rescue {}
But this is not appropriate way, Please suggest me how can I load all yaml files access with ENV variable that.
Assuming that your YAML files are placed in the config folder, in your application.rb you can do this right under the requires (before the module definition)
APP_YAML = YAML::load_file(File.join(File.dirname(File.expand_path(__FILE__)), 'application.yml'))
LINKED_IN = YAML::load_file(File.join(File.dirname(File.expand_path(__FILE__)), 'linked_in.yml'))
This way, you can then access the contents of the file in a constant that is available everywhere in the app ie. LINKED_IN["secret"]
This is a great way to handle constants that you don't want to check in to source control, but actually I've found that using Figaro is the best way to handle constants. Essentially, Figaro will autogenerate/load an application.yml and all you have to do is put your constants in there.
After this, you can access with ENV["LINKED_IN_SECRET"] - as a plus, this emulates how Heroku would do it with their config:set variable system so you don't have to worry about environment changes :)

How to share constant in different controllers and models and view in Rails 3

What is the best practice to share an global variable
eg: host = test123.com
and I Can use "host" every where ?
I will used it as CONSTANT to show my email in many places,
So I don't want to hardcode my email address everywhere!
Thanks~
I will typically create a file in my initializer directory or add to my environment (devel or production) and declare my variable with caps.
production.rb
SECRET_KEY = "blahblah"
Then across my app, I can reference to this variable by using the ENV
So, in my view, I would type ENV["SECRET_KEY"] or just SECRET_KEY
You should really avoid doing this. That being said, ::HOST = 'test123.com'
I will used it as CONSTANT to show my email in many places,
if you are only using this for display purposes - then consider putting it in en.yml file (and other locale files if desired)
see http://guides.rubyonrails.org/i18n.html#adding-translations
Just check this out http://railscasts.com/episodes/85-yaml-configuration-file . This is the standard way of defining global configurations in Rails app.

Where to store (structured) configuration data in Rails

For the Rails 3 application I'm writing, I am considering reading some of the configuration data from XML, YAML or JSON files on the local filesystem.
The point is: where should I put those files? Is there any default location in Rails apps where to store this kind of content?
As a side note, my app is deployed on Heroku.
What I always do is:
If the file is a general configuration file: I create a YAML file in the directory /config with one upper class key per environment
If I have a file for each environment (big project): I create one YAML per environment and store them in /config/environments/
Then I create an initializer where I load the YAML, I symbolize the keys of the config hash and assign it to a constant like APP_CONFIG
I will usually adopt this method :
a config/config.yml
development:
another_key: "test"
app_name: "My App"
test:
another_key: "test"
production:
prova: "ciao"
then create a ostruct in a initializer
#config/initializer/load_config.rb
require 'ostruct'
config = OpenStruct.new(YAML.load_file("#{RAILS_ROOT}/config/config.yml"))
::AppSetting = OpenStruct.new(config.send(RAILS_ENV))
No DB table, per environment setup and you could retrive info in a simple way
AppSetting.another_key
AppSetting.app_name
here a reference
have a nice day!
You can also include it in a model so you can call Settings.var_name from anywhere in your app and it will parse the file for the right environment.
With settingslogic gem:
class Settings < Settingslogic
source "#{Rails.root}/config/settings.yml"
namespace Rails.env
end
Rails creates a config directory by default, containing a lot of configuration info for your application, including the database and environment information. I think that's a logical first place to consider.
A second choice would be the app directory, which contains all the models, views and controllers for the application, but I think of that directory as containing executable code and its templates, so I'd go with the config directory, personally.

Resources