Last active
December 28, 2015 22:09
-
-
Save ngauthier/7570010 to your computer and use it in GitHub Desktop.
Reportable Concern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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.