Skip to content

Instantly share code, notes, and snippets.

@joefiorini
Created January 7, 2012 05:34
Show Gist options
  • Save joefiorini/1573904 to your computer and use it in GitHub Desktop.
Save joefiorini/1573904 to your computer and use it in GitHub Desktop.
Camelize Hash keys to return in JSON request. In other words, idiomatic JSON for your Rubies. Consider this pseudo-code as it's about 40% untested.
def HashExtensions(hash)
hash.extend(HashExtensions)
end
module HashExtensions
def camelize_keys
dup.camelize_keys!
end
def camelize_keys!
keys.each do |k|
new_key = k.to_s.camelize(:lower)
new_key = new_key.to_sym if k.is_a? Symbol
self[new_key] = self.delete(k)
end
self
end
end
class YourModel < ActiveRecord::Base
def as_json
HashExtensions(attributes).camelize_keys.to_json
end
end
@jonathandean
Copy link

If ActiveSupport is available you can use:

# with a single level hash
hash.transform_keys{ |key| key.to_s.camelize(:lower) }
# with nested hashes
hash.deep_transform_keys{ |key| key.to_s.camelize(:lower) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment