Sha256: 20679632c1aa9e699f735fb515d1057a3b3fad2a35b32fb400ec35b486b4eef4

Contents?: true

Size: 1.37 KB

Versions: 8

Compression:

Stored size: 1.37 KB

Contents

module Nazrin
  module ActiveRecord
    class DataAccessor
      def initialize(model, options)
        @model = model
        @options = options
      end

      # a list of all matching AR model objects
      def results(client)
        @client = client

        res = @client.search
        collection = load_all(res.data.hits.hit.map(&:id))

        if @client.parameters[:size] && @client.parameters[:start]
          total_count = res.data.hits.found

          Nazrin::PaginationGenerator.generate(
            collection,
            current_page: current_page,
            per_page: @client.parameters[:size],
            total_count: total_count,
            last_page: last_page(total_count))
        else
          collection
        end
      end

      # load from activerecord
      def load_all(ids)
        records_table = {}
        @options.each do |k, v|
          @model = @model.send(k, v)
        end
        @model.where(id: ids).each do |record|
          records_table[record.id] = record
        end
        ids.map do |id|
          records_table.select { |k, _| k == id.to_i }[id.to_i]
        end.reject(&:nil?)
      end

      private

      def last_page(total_count)
        (total_count / @client.parameters[:size].to_f).ceil
      end

      def current_page
        (@client.parameters[:start] / @client.parameters[:size].to_f).ceil + 1
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
nazrin-2.1.2 lib/nazrin/active_record/data_accessor.rb
nazrin-2.1.1 lib/nazrin/active_record/data_accessor.rb
nazrin-2.1.0 lib/nazrin/active_record/data_accessor.rb
nazrin-2.0.0 lib/nazrin/active_record/data_accessor.rb
nazrin-2.0.0.rc2 lib/nazrin/active_record/data_accessor.rb
nazrin-2.0.0.rc1 lib/nazrin/active_record/data_accessor.rb
nazrin-1.0.1 lib/nazrin/active_record/data_accessor.rb
nazrin-1.0.0 lib/nazrin/active_record/data_accessor.rb