Skip to content

Instantly share code, notes, and snippets.

@ashishwadekar
Forked from alebian/json_serializer.rb
Created March 18, 2019 11:02
Show Gist options
  • Save ashishwadekar/d3e8cddd2e3762ede13984f7927692d4 to your computer and use it in GitHub Desktop.
Save ashishwadekar/d3e8cddd2e3762ede13984f7927692d4 to your computer and use it in GitHub Desktop.
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