Skip to content

Instantly share code, notes, and snippets.

@nowk
Created July 4, 2012 15:38
Show Gist options
  • Save nowk/3047921 to your computer and use it in GitHub Desktop.
Save nowk/3047921 to your computer and use it in GitHub Desktop.
Paginated mapping to json
def mapping_for_js(resource, options={})
resource_name = resource.is_a?(ActiveRecord::Relation) ?
resource.name.tableize : resource.class.to_s.underscore
payload = {
resource_name => JSON.parse(resource.to_json(options[:to_json]))
}
# only merge if paginated
payload.merge!(:paginate => {
:total_entries => resource.total_entries,
:prev_page => resource.previous_page,
:next_page => resource.next_page,
:page => resource.current_page,
:total_pages => resource.total_pages,
:per_page => resource.per_page
}) if (resource.try(:per_page) rescue false)
# TODO more solid way to ensure this is a paginated object to use with
# either via kamamri and will_paginate
# though 'per_page' is probably a solid sign it does
payload = payload.to_json if options[:force_to_json]
unless options[:instance_name].blank?
var_name = "@#{options[:instance_name]}"
# if we are setting instance variable, we also want to send that back
# as the return
instance_variable_set var_name, payload
return instance_variable_get var_name
end
payload
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment