A demo of YAML anchors, references and nested values
require 'rubygems' | |
require 'yaml' | |
# A demonstration of YAML anchors, references and handling of nested values | |
# For more info, see: | |
# http://atechie.net/2009/07/merging-hashes-in-yaml-conf-files/ | |
stooges = YAML::load( File.read('stooges.yml') ) | |
# => { | |
# "default" => { | |
# "URL" => "stooges.com", | |
# "throw_pies?" => true, | |
# "stooges" => { | |
# "larry" => "first_stooge", | |
# "moe" => "second_stooge", | |
# "curly" => "third_stooge" | |
# } | |
# }, | |
# "development" => { | |
# "URL" => "stooges.local", | |
# "throw_pies?" => true, | |
# "stooges" => { # where are the other 3 stooges? | |
# "shemp" => "fourth_stooge" | |
# } | |
# }, | |
# "test" => { | |
# "URL" => "test.stooges.qa", | |
# "throw_pies?" => true, | |
# "stooges" => { | |
# "larry" => "first_stooge", # all stooges are here because... | |
# "moe" => "second_stooge", # ...we used `stooges: <<: *stooge_list` in stooges.yml | |
# "curly" => "third_stooge", | |
# "shemp" => "fourth_stooge" | |
# } | |
# } | |
# } |
default: &DEFAULT | |
URL: stooges.com | |
throw_pies?: true | |
stooges: &stooge_list | |
larry: first_stooge | |
moe: second_stooge | |
curly: third_stooge | |
development: | |
<<: *DEFAULT | |
URL: stooges.local | |
stooges: | |
shemp: fourth_stooge | |
test: | |
<<: *DEFAULT | |
URL: test.stooges.qa | |
stooges: | |
<<: *stooge_list | |
shemp: fourth_stooge |
# Set custom config options in config/app_cong.yml | |
# @examples: | |
# AppConf.use_ssl? # => false | |
# AppConf.site_color # => "purple" | |
class AppConf | |
SETTINGS_HASH = YAML.load_file( Rails.root.join('config', 'app_conf.yml') )[Rails.env] | |
class << self | |
def method_missing(method, *args) | |
SETTINGS_HASH[method.to_s] # could use ClassyStruct here for more features and better performance | |
end | |
end | |
end |
This comment has been minimized.
This comment has been minimized.
a lot of thanks |
This comment has been minimized.
This comment has been minimized.
Yeah, thanks so so much! I wasn't sure how to get round the lack of deep mergingin yaml, but your strategy totally solved it for me :) |
This comment has been minimized.
This comment has been minimized.
Good example, much appreciated. |
This comment has been minimized.
This comment has been minimized.
Is there a |
This comment has been minimized.
This comment has been minimized.
@fulldecent: not, it shouldn't work with array. See YAML refcard for spec 1.1.
|
This comment has been minimized.
This comment has been minimized.
Thanks for this @bowsersenior. default_array: &DEFAULT_ARRAY
- item_1
- item_2
my_array: *DEFAULT_ARRAY
my_other_array:
- item_3
- item_4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Thanks for your nice clean example of this.