Sha256: 09df700cb2420c2d442691cc6414a85321c64ba2a7c8455569677180e7a8d115

Contents?: true

Size: 1.6 KB

Versions: 13

Compression:

Stored size: 1.6 KB

Contents

module RestPack::Serializer
  class Options
    attr_accessor :page, :page_size, :include, :filters, :serializer,
                  :model_class, :scope, :context, :include_links

    def initialize(serializer, params = {}, scope = nil, context = {})
      params.symbolize_keys! if params.respond_to?(:symbolize_keys!)

      @page = 1
      @page_size = RestPack::Serializer.config.page_size
      @include = []
      @filters = filters_from_params(params, serializer)
      @serializer = serializer
      @model_class = serializer.model_class
      @scope = scope || model_class.send(:all)
      @context = context
      @include_links = true

      @page = params[:page].to_i if params[:page]
      @page_size = params[:page_size].to_i if params[:page_size]
      @include = params[:include].split(',').map(&:to_sym) if params[:include]
    end

    def scope_with_filters
      scope_filter = {}
      @filters.keys.each do |filter|
        value = @filters[filter]
        if value.is_a?(String)
          value = value.split(',')
        end
        scope_filter[filter] = value
      end

      @scope.where(scope_filter)
    end

    def default_page_size?
      @page_size == RestPack::Serializer.config.page_size
    end

    def filters_as_url_params
      @filters.sort.map {|k,v| "#{k}=#{v.join(',')}" }.join('&')
    end

    private

    def filters_from_params(params, serializer)
      filters = {}
      serializer.filterable_by.each do |filter|
        [filter, "#{filter}s".to_sym].each do |key|
          filters[filter] = params[key].to_s.split(',') if params[key]
        end
      end
      filters
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
restpack_serializer-0.4.25 lib/restpack_serializer/options.rb
restpack_serializer-0.4.24 lib/restpack_serializer/options.rb
restpack_serializer-0.4.23 lib/restpack_serializer/options.rb
restpack_serializer-0.4.21 lib/restpack_serializer/options.rb
restpack_serializer-0.4.20 lib/restpack_serializer/options.rb
restpack_serializer-0.4.19 lib/restpack_serializer/options.rb
restpack_serializer-0.4.18 lib/restpack_serializer/options.rb
restpack_serializer-0.4.17 lib/restpack_serializer/options.rb
restpack_serializer-0.4.16 lib/restpack_serializer/options.rb
restpack_serializer-0.4.15 lib/restpack_serializer/options.rb
restpack_serializer-0.4.14 lib/restpack_serializer/options.rb
restpack_serializer-0.4.13 lib/restpack_serializer/options.rb
restpack_serializer-0.4.12 lib/restpack_serializer/options.rb