-
-
Save mufasa71/8741945 to your computer and use it in GitHub Desktop.
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