Last active
December 10, 2015 08:28
-
-
Save dieb/4407514 to your computer and use it in GitHub Desktop.
json_version_of for Rails ActiveRecord::Base models
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 rename_keys(obj, old_key, new_key) | |
renamer = lambda { |i| i.rename_key(old_key, new_key) } | |
case obj | |
when Array then obj.collect(&renamer) | |
when Hash then renamer.call(obj) | |
else obj | |
end | |
end | |
def json_version_of(model, options={}) | |
as = options.delete(:as) | |
repr = JSON.parse(model.to_json(options)) | |
if !as.nil? and options.has_key?(:include) | |
rename_keys(repr, options[:include].to_s, as.to_s) | |
else | |
repr | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment