-
-
Save ashishwadekar/d3e8cddd2e3762ede13984f7927692d4 to your computer and use it in GitHub Desktop.
Use PostgreSQL JSON result in Rails http://blog.redpanthers.co/create-json-response-using-postgresql-instead-rails/
This file contains hidden or 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 JsonSerializer | |
module_function | |
# | |
# Usage: | |
# JsonSerializer.find_by_id(User, 1, only: [:id, email, :address], except: [:address]) | |
# | |
def find_by_id(klass, id, options = {}) | |
sql = "SELECT row_to_json(results) FROM ( | |
SELECT #{selected_attributes(klass, options)} | |
FROM #{table_name(klass)} | |
WHERE id = #{id} | |
) as results" | |
find_by_sql(sql) | |
end | |
# | |
# Usage: | |
# JsonSerializer.find_all(User, only: [:id, email, :address], except: [:address]) | |
# | |
def find_all(klass, options = {}) | |
sql = "SELECT array_agg(row_to_json(results)) FROM ( | |
SELECT #{selected_attributes(klass, options)} | |
FROM #{table_name(klass)} | |
) as results" | |
find_by_sql(sql) | |
end | |
def find_by_sql(sql) | |
result = ActiveRecord::Base.connection.execute(sql) | |
return '{}' if result.ntuples == 0 | |
result.getvalue(0, 0) | |
end | |
def table_name(klass) | |
klass.name.underscore.pluralize | |
end | |
def selected_attributes(klass, options) | |
only = options[:only].present? ? options[:only].map { |a| a.to_s } : [] | |
exceptions = options[:except].present? ? options[:except].map { |a| a.to_s } : [] | |
attributes = only.empty? ? klass.column_names : only | |
attributes = attributes.delete_if { |a| exceptions.include?(a) } | |
attributes.join(', ') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment