Skip to content

Instantly share code, notes, and snippets.

@dieb
Last active December 10, 2015 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dieb/4407514 to your computer and use it in GitHub Desktop.
Save dieb/4407514 to your computer and use it in GitHub Desktop.
json_version_of for Rails ActiveRecord::Base models
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