class Mincer::Processors::PgJsonDumper::Processor

Public Class Methods

new(mincer, options = {}) click to toggle source
# File lib/mincer/processors/pg_json_dumper/processor.rb, line 6
def initialize(mincer, options = {})
  @mincer, @args, @relation, @options = mincer, mincer.args, mincer.relation, options
end

Public Instance Methods

apply() click to toggle source
# File lib/mincer/processors/pg_json_dumper/processor.rb, line 10
def apply
  @relation
end
to_json() click to toggle source
# File lib/mincer/processors/pg_json_dumper/processor.rb, line 14
def to_json
  if dump_supported?
    result = Mincer.connection.select_all(json_query).first['json']
    return result unless @options[:singularize]
    return (result[1..-2].presence || '{}') unless @options[:root]
    (result.sub('[', '').sub(/(\])}$/, '}').presence || '{}')
  else
    warn 'To dump data to json with postgres you need to use postgres server version >= 9.2'
  end
end

Private Instance Methods

base_sql() click to toggle source
# File lib/mincer/processors/pg_json_dumper/processor.rb, line 39
def base_sql
  @mincer.sql
end
basic_json_query(root = 'json', meta = false) click to toggle source

Query for basic json generation. Ex: [{'id': 1}, {…}]

# File lib/mincer/processors/pg_json_dumper/processor.rb, line 44
        def basic_json_query(root = 'json', meta = false)
          meta_sql = if meta
            if meta.is_a?(Hash) && meta[:total_count]
              @mincer.relation.instance_variable_set(:@total_count, meta[:total_count])
            end
            ", #{@mincer.total_pages} AS total_pages, #{@mincer.total_count} AS total_count, #{@mincer.current_page} AS current_page, #{@mincer.limit_value} AS per_page"
          else
            ''
          end
          <<-SQL
            SELECT COALESCE(array_to_json(array_agg(row_to_json(subq))), '[]') AS #{root} #{meta_sql}
            FROM (#{base_sql}) as subq
          SQL
        end
dump_supported?() click to toggle source
# File lib/mincer/processors/pg_json_dumper/processor.rb, line 27
def dump_supported?
  Mincer.postgres? && (Mincer.connection.send(:postgresql_version) >= 90200)
end
json_query() click to toggle source
# File lib/mincer/processors/pg_json_dumper/processor.rb, line 31
def json_query
  if @options[:root]
    json_query_with_root(@options[:root], @options[:meta])
  else
    basic_json_query
  end
end
json_query_with_root(root, meta) click to toggle source

Generates json with root. Ex: If root = 'items' resulting json will be { 'items' => […] } When `meta` passed will add pagination data(Experimental!!!)

# File lib/mincer/processors/pg_json_dumper/processor.rb, line 61
        def json_query_with_root(root, meta)
          <<-SQL
            SELECT row_to_json(t) as json FROM ( #{basic_json_query(root, meta)} ) as t
          SQL
        end