Created
January 7, 2012 05:34
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class YourModel < ActiveRecord::Base | |
def as_json | |
HashExtensions(attributes).camelize_keys.to_json | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If
ActiveSupport
is available you can use: