recursive_symbolize_keys in ruby

Result of not using recursive_symbolize_keys, we are getting APP_CONFIG as a string

$>> APP_CONFIG = YAML.load_file(“#{RAILS_ROOT}/config/settings.yml”)[RAILS_ENV]

=> {“xpmm”=>{“admin_password”=>123, “admin”=>”admin”, “bosh_service”=>”/http-bind”, “muc_component”=>”conference.client381”, “bosh_host”=>”site”, “strophe_debug”=>false, “host”=>”client38”}, “site_url”=>”http://site”, “admin_email”=>”someone@gmail.com”, “chat_host”=>”chat.site”, “dropio_api_key”=>”aa6b700a23a69a6051802a6a6d134e8c5e76e02e”, “site_name”=>”site”}

Result of using recursive_symbolize_keys, we are getting APP_CONFIG as a Key–>Symbol format

$>>APP_CONFIG = YAML.load_file(“#{RAILS_ROOT}/config/settings.yml”)[RAILS_ENV].recursive_symbolize_keys!

=> {:dropio_api_key=>”aa6b700a23a69a6051802a6a6d134e8c5e76e02e”, :site_name=>”site”, : xpmm=>{:muc_component=>”conference.client381″, :bosh_host=>”site”, :strophe_debug=>false, :admin_password=>123, :host=>”client38″, :admin=>”admin”, :bosh_service=>”/http-bind”}, :site_url=>”http://site”, :admin_email=>”someone@gmail.com”, :chat_host=>”chat.site”}

To do that :-

in /config/initializers/load_config.rb

require “#{RAILS_ROOT}/lib/ruby_classes_extensions”
APP_CONFIG = YAML.load_file(“#{RAILS_ROOT}/config/settings.yml”)[RAILS_ENV].recursive_symbolize_keys!

in /lib/ruby_classes_extensions.rb

class Hash
def recursive_symbolize_keys!
symbolize_keys!
values.select{ | v | v.is_a?( Hash ) }.each{ | h | h.recursive_symbolize_keys! }
self
end
end

Advertisements

1 thought on “recursive_symbolize_keys in ruby”

  1. The issue with this is if there are arrays in your hash. May be better to have a generic method that can symbolize more complex collections:

    def rsk! coll
    if coll.respond_to? :each
    coll.symbolize_keys! if coll.is_a( Hash )
    coll.each do |el|
    rsk! el
    end
    end
    coll
    end

Comments are closed.