Sha256: 453a62088e0ba12d020b2adb6a560fce4e3fc2478ce85af1b0d621fd900675bf

Contents?: true

Size: 1.4 KB

Versions: 7

Compression:

Stored size: 1.4 KB

Contents

module Snaptable
  module Constructor
    module Collection

      def collection
        @collection ||= if Snaptable.use_permission 
          current_permission.records(params[:controller], model, @token)
        else
          model
        end.includes(belongs_to_associations)
      end

      def records
        @records ||= filter(collection).paginate(page: params[:page], per_page: 30).order(sort_column + " " + sort_direction)
      end

      def filter(collection)
        if options[:search] == true
          collection.joins(search_associations).where(query, query: "%#{params[:query]}%", id: params[:query].to_i)
        else
          collection
        end
      end

      private

      def query
        query_fields.map do |key, values|
          values.map do |value|
            values.map{ |v| "#{key}.#{v} LIKE :query OR"}.join(" ")
          end
        end.join(" ") + " #{column_name('id')} = :id"
      end

      def query_fields
        if self.class.const_defined?(:Search)
          self.class::Search.fields
        else
          { model.table_name => model.columns.select{ |c| c.type == :string }.map{ |c| c.name } }
        end
      end

      def search_associations
        self.class::Search.associations if self.class.const_defined?(:Search)
      end

      def belongs_to_associations
        model.reflect_on_all_associations(:belongs_to).map{ |a| a.name }
      end

    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
snaptable-0.6.1 lib/snaptable/constructor/collection.rb
snaptable-0.6.0 lib/snaptable/constructor/collection.rb
snaptable-0.5.1 lib/snaptable/constructor/collection.rb
snaptable-0.5.0 lib/snaptable/constructor/collection.rb
snaptable-0.4.2 lib/snaptable/constructor/collection.rb
snaptable-0.4.1 lib/snaptable/constructor/collection.rb
snaptable-0.4.0 lib/snaptable/constructor/collection.rb