Skip to content

Instantly share code, notes, and snippets.

@kivanio
Forked from ngauthier/reportable.rb
Created March 31, 2014 14:33
Show Gist options
  • Save kivanio/9893701 to your computer and use it in GitHub Desktop.
Save kivanio/9893701 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