Skip to content

Instantly share code, notes, and snippets.

@ngauthier
Last active December 28, 2015 22:09
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ngauthier/7570010 to your computer and use it in GitHub Desktop.
Save ngauthier/7570010 to your computer and use it in GitHub Desktop.
Reportable Concern
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
@ngauthier
Copy link
Author

I created this to spit out raw (or simple processing by postgresql) data to be used by d3 in a page. Skips ActiveRecord and Ruby JSON generation. PG does the json building from the query.

Since they're class methods, you can chain it onto any scope you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment