Skip to content

Instantly share code, notes, and snippets.

@mufasa71
Forked from ngauthier/reportable.rb
Created January 31, 2014 20:07
Show Gist options
  • Save mufasa71/8741945 to your computer and use it in GitHub Desktop.
Save mufasa71/8741945 to your computer and use it in GitHub Desktop.
module Reportable
extend ActiveSupport::Concern
module ClassMethods
# Chain on a scope and specify the fields to extract.
# Example:
# User.enabled.report %{
# :email_opt_in,
# 'created_at as sign_up_date'
# }
#
# => JSON string [{email_opt_in: true, created_at: "timestamp"}]
#
def report(*fields)
select(*fields).pg_json
end
def pg_json
connection.execute(%{
select array_to_json(array_agg(row_to_json(t))) as result
from (#{all.to_sql}) t
})[0]["result"] || []
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment