class Praxis::Extensions::Pagination::OrderingParams::DSLCompiler

DSL for restricting how to order. It allows the concrete list of the fields one can use (through ‘by_fields’) It also allows to enforce that list for all positions of the ordering definition (through ‘enforce_for :all|:first’)

By default, only the first ordering position will be subject to that enforcement (i.e., 'enforce_for :first' is the default)

Example

attribute :order, Praxis::Types::OrderingParams.for(MediaTypes::Bar) do

by_fields :id, :name
enforce_for :all

end

Public Class Methods

validate_field(type, path) click to toggle source
# File lib/praxis/extensions/pagination/ordering_params.rb, line 51
def self.validate_field(type, path)
  main, rest = path
  next_attribute = type.respond_to?(:member_attribute) ? type.member_type.attributes[main] : type.attributes[main]

  return main unless next_attribute

  return nil if rest.nil?

  validate_field(next_attribute.type, rest)
end

Public Instance Methods

by_fields(*fields) click to toggle source
# File lib/praxis/extensions/pagination/ordering_params.rb, line 26
def by_fields(*fields)
  requested = fields.map(&:to_sym)

  errors = []
  requested.each do |field|
    if (failed_field = self.class.validate_field(target.media_type, field.to_s.split('.').map(&:to_sym)))
      errors += ["Cannot order by field: '#{field}'. It seems that the '#{failed_field}' attribute is not defined in the current #{target.media_type} structure (or its subtree)."]
    end
  end
  raise errors.join('\n') unless errors.empty?

  target.fields_allowed = requested
end
enforce_for(which) click to toggle source
# File lib/praxis/extensions/pagination/ordering_params.rb, line 40
def enforce_for(which)
  case which.to_sym
  when :all
    target.enforce_all = true
  when :first
    # nothing, that's the default
  else
    raise "Error: unknown parameter for the 'enforce_for' : #{which}. Only :all or :first are allowed"
  end
end