rails: yml merging - ruby-on-rails

Say I have a yml file for my rails configuration...
settings.yml
defaults: &defaults
interceptor_email: robot#wearemanalive.com
development:
<<: *defaults
test:
<<: *defaults
production:
<<: *defaults
and I want to have another yml file that is NOT included in version control that each developer maintains locally...
user_settings.yml
development:
interceptor_email: userfoo#domain.com
How can I merge these keys? I am processing my yml files with esb, so that is also an option. Just having trouble figuring out how to do it. I have it setup so keys fallback to the defaults if a key is missing for my environments.

Can't you read the two yml files separately?
settings = YAML.load(path_to_settings)[RAILS_ENV].symbolize_keys
user_settings = YAML.load(path_to_user_settings)[RAILS_ENV].symbolize_keys
settings.merge!(user_settings)
Now you should have the hash value of the settings, then you can merge the hash if you want. If the second hash has the same key as the first hash, the first one will be overwritten.

This is how I do it (disclaimer, I just wrote it, so it doesn't have unit tests yet etc...I'll update this as I improve on it):
require 'yaml'
# read config files (currently only yaml supported), merge user config files over
# defaults and make the parsed data available to the rest of your application.
#
module YourNamespace class Config
attr_reader :files, :get
# Accepts a string filename or an array of string filenames to parse.
# If an array is supplied, values from later files will override values
# of earlier files with the same name.
# Will choke if YAML.load_file returns false (invalid or empty file)
#
def initialize( files )
#files = files.respond_to?( 'map' ) ? files : [ files ]
#get = #files \
\
.map { | file | YAML.load_file file } \
.reduce( {}, :merge! )
;
end
end end
You can call it like this:
config = YourNamespace::Config.new 'config.yml'
# or have the second one override the first
#
config = YourNamespace::Config.new [ 'config-defaults.yml', 'config.yml' ]
And if you want to go fancy, there's a lot of room for improvement here. Ideally make ´Config´ an interface that does not deal with files, and implement in YamlConfig, IniConfig, CliConfig, DbConfig, CookieConfig. That way if you decide one day the that that new config format super seeding yaml is so cool, you can easily change it without breaking anything. And you can have the command line configuration options easily override the ones coming from the configuration files. And you can reuse the config module for any ruby project regardless of where the config values come from. Or maybe just stop inventing hot water. A quick browse makes me think there's some pretty hot water over there...
Next write some documentation, unit tests, input validation, error handling and create some fancy read/write accessors for the config values. Maybe you'd like to be able to ask for a config value like this instead of writing arrays and hashes all the time:
config.get 'app.component.section.setting'
# or this if you want to keep them separate:
#
config.get( 'app', 'component', 'section', 'setting' )

Related

Rails: configuring applications

I am reading and coding along with a tutorial.
I have an application.yml file with some constants created to hold data. To include those constants in ENV and initialize them at start, this code was given :
config_file = Rails.application.config_for(:application) #this is the bothersome part
config_file.each do |key,value|
ENV[key] = value
end unless config_file.nil?
I fail to fully understand this code. In particular, on the first line, where do the chained objects come from what do they mean and how do I create such on my own ?
It loads data from a config file into the app. The example from the docs about #config_for:
#config/app.yml:
production:
url: http://127.0.0.1:8080
namespace: my_app_production
development:
url: http://localhost:3001
namespace: my_app_development
If you do rails c and type Rails.application.config_for(:app) into the console, you'll get:
{"url"=>"http://localhost:3001", "namespace"=>"my_app_development"}
which is just a regular hash you can loop through using #each or access it's values through keys.

What's a good approach for loading a YAML config in Ruby but setting default values?

I am going to load some app configurations from a YAML file:
# YAML config file
app_name: "Example"
app_path: ~/path/to/app
So I load them:
app_config = YAML::load_file("config.yml")
What would be a clean way to set defaults if some key/value is missing?
You should prepare a default hash, and then overwrite the values from the configure by merging the hash.
default_app_config = {
"app_name" => "Default name",
"app_path" => "default/path",
...,
}
app_config = default_app_config.merge(YAML.load_config("config.yml"))
Since app_config would simply be a Hash at the point that you've loaded your YAML config, you can use Hash-like tests, like this:
name = app_config['name'] || 'default'
This works great if you have a very minimal number of these checks to make, particularly if they're located right near the point that you load the YAML config.
However, you can update your config hash with the defaults, like this:
app_config['name'] ||= 'default'
That way, you don't have to keep checking to see if the key exists throughout the rest of your code.
Something like this at the point that you load the YAML might work:
app_config = YAML::load_file("config.yml")
# Set default values
app_config['app_name'] ||= "Example"
app_config['app_path'] ||= "~/path/to/app"
That will keep the rest of your code simple and uncomplicated by applying default values. These are DRY defaults for YAML config files.

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.

Accessing config from application.rb in Controller (Rails 3)

I'm trying to add two extra config options to my application.rb so I can read them out in controllers.
# Extra
config.twitter.key = 'foo'
config.twitter.secret = 'bar'
I am trying to access them using three suggested methods:
self.config.twitter.key # Should be extended through ApplicationController Base
config.twitter.key # Inherited but with different syntax
CONFIG['twitter']['key'] #some massive magical array that apparently exists somewhere
They all give me different kinds of error when I pass them through the "debug" method, E.g:
debug self.config.twitter.key # undefined method `key' for nil:NilClass
So, whats going on?
I believe you've got a slightly incorrect idea behind what your expectations for the config/application.rb is providing you. The ActiveRecord::Base and ActiveController::Base eigenclasses use the Rails::Application::Configuration class that is configured in config/application.rb. The attributes aren't available in classes that descend from either of the Base classes, nor their eigenclasses. This is why you are running into errors in ApplicationController.
There are generally two ways to make configuration initializations in a Rails app. The first way is to create a configuration module and then load values into it via initializer:
First, create a Twiter Config module:
#lib/twitter_config.rb
module TwitterConfig
def self.config
##config ||= {}
end
def self.config=(hash)
##config = hash
end
end
Create a YAML config file:
# config/twitter.yaml
development: &base
key: "foo"
secret: "bar"
test:
<<: *base
key: "foo2"
production:
<<: *base
secret: "barbar"
Alternatively, if you don't intend to add config/twitter.yaml to your SCM, you can just skip this and set the key and secret via environment variables. This would be the suggested solution for an application with a public SCM repository deploying on Heroku.
Then load and set the value via an initializer:
#config/initializers/01_twitter.rb
require 'twitter_config'
TwitterConfig.config = YAML.load_file("config/config.yml")[Rails.env].symbolize_keys
It's generally a best practice to number your initializer files as Rails will load them in order according to their filename. If you are initializing a datastore and that is critical for other steps, then it needs the lowest number. Alternatively, if you are using environment variables, this would be the init file:
#config/initializers/01_twitter.rb
require 'twitter_config'
TwitterConfig.config[:key] = ENV['twitter_config_key']
TwitterConfig.config[:secret] = ENV['twitter_config_secret']
Throughout the Rails application, you now have access to the config values with TwitterConfig.config[:key] & TwitterConfig.config[:secret]. You can include the module as well, just watch out for conflicts.
You can also just load the values as a global constant. It feels a bit ugly to me though:
#config/application.rb
TWITTER_CONFIG = YAML.load_file("config/twitter.yaml")[Rails.env]
I've tried this and seems to be working, you can use ::Rails.application.config.
For example I'm using it to get the correct time_zone set in the application like this:
Rails.application.config.time_zone
I found it thanks to the less-rails code: https://github.com/metaskills/less-rails/blob/master/lib/less/rails/helpers.rb
So you can declare this in your application.rb or in any enviroment file:
config.twitter_key = 'foo'
And then read it like so anywhere in your code:
Rails.application.config.twitter_key
You might want to consider using a yaml file approach.
In application.rb
CONFIG = YAML.load_file("config/config.yml")[Rails.env]
In config/config.yml
development: &base_config
twitter_key = "foo"
twitter_secret = "bar"
test:
<<: *base_config
twitter_key = "foo2"
production:
<<: *base_config
twitter_secret = "barbar"
Same usage as before with definable attributes on an environment level with overloading.
CONFIG['twitter_key']
A small update to the widely accepted answer here : Accessing config from application.rb in Controller (Rails 3)
The methods inside the module TwitterConfig should be class methods (or module methods if you prefer it that way). They can't be instance methods.
Sorry to put this in an answer, but I could not find a way to comment on that answer.
Just put a file in config/initializers/ like app_config.rb If you use ENV constant you can later on easily deploy to Heroku setting the values with the heroku config:add twitter_key=mypublickey command.
Something like this:
## config/initializers/app_config.rb
unless Rails.env.production?
ENV['twitter_key'] = 'foo'
ENV['twitter_secret'] = 'bar'
end
You keep your production keys out of revision control and don't need to dribble with YAML-files.

What is the best way to keep web app config?

If I have some config for web admin to set e.g. number of post per page, some enum showing choice. How should I keep this settings in db ? Should I serialize it and save as blob.
Thanks,
I using rails and I want it to dynamically change this setting through web interface, so I think environment.rb would not fit this situation. So I should have a extra table with two tuples as name, value ?
Most languages/frameworks have a config file of sorts. such as the web.config in ASP or the environment.rb files in RoR. You could use one of these.
Or failing that have a key value pair table in your database.
If you're wanting to do this dynamically through the website I would definitely go for the key value pair table.
For the dynamic config values, you should create a model called Configuration with keys and values. I generally have multiple value columns (for number, string, and date) and then call the appropriate method for the configuration.
For "enums" you should create lookup tables with foreign key relationships to where they attach. For example if you have a Post model and you want an enumeration of Category, you should make the Post belong_to :category and Category has_many :posts.
Use a YAML file. YAML is way simpler than XML.
Make a file called "config.yml" in "config" directory. And load the file using YAML::load(). You can make a setting for each environment by naming the first level as environment (e.g., production, development, test).
See this episode of RailsCasts for details.
If you are using asp.net you can use the Web.Config file.
See Asp .net Web.config Configuration File
You could to create a single table in your database to store key-value pairs.
This is what I use. Got the idea from elsewhere, but the implementation is mine. Pulled from a production project of mine:
class AppConfig
# Loads a YAML configuration file from RAILS_ROOT/config/. The default file
# it looks for is 'application.yml', although if this doesn't match your
# application, you can pass in an alternative value as an argument
# to AppConfig.load.
# After the file has been loaded, any inline ERB is evaluated and unserialized
# into a hash. For each key-value pair in the hash, class getter and setter methods
# are defined i.e., AppConfig.key => "value"
# This allows you to store your application configuration information e.g., API keys and
# authentication credentials in a convenient manner, external to your application source
#
# application.yml example
#
# :defaults: &defaults
# :app_name: Platform
# :app_domain: dev.example.com
# :admin_email: admin#example.com
# :development:
# <<: *defaults
# :test:
# <<: *defaults
# :production:
# <<: *defaults
# :app_domain: example.com
#
# For example will result in AppConfig.app_domain => "dev.example.com"
# when Rails.env == "development"
#
class << self
def load(file='application.yml')
configuration_file = File.join Rails.root, 'config', file
File.open(configuration_file) do |configuration|
configuration = ERB.new(configuration.read).result
configuration = YAML.load(configuration)[Rails.env.to_sym]
configuration.each do |key, value|
cattr_accessor key
send "#{key}=", value
end
end if File.exists? configuration_file
end
end
end
AppConfig.load
Create config/initializers/app_config.rb and paste the above code into it. I'm going to make this into a gem. I figure other people will find it useful.
EDIT: Just saw you wish to edit the config as the app runs via a web based interface. You could do this with this method as both getter and setter methods are defined for each attribute.
in your controller:
def update
params[:configuration].each { |k,v| AppConfig.send "#{k}=", v }
…
end
I don't find a model is the right solution here. Forget about the DB overheard, the idea of being able to instantiate something that controls app configuration doesn't make sense. What's more how you implement it? An instance for each tuple?! It should be a singleton class.

Resources