Class: Praxis::Extensions::Pagination::OrderingParams::DSLCompiler

Inherits:
Attributor::DSLCompiler
  • Object
show all
Defined in:
lib/praxis/extensions/pagination/ordering_params.rb

Overview

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.validate_field(type, path) ⇒ Object



51
52
53
54
55
56
57
58
59
60
# 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

Instance Method Details

#by_fields(*fields) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# 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) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# 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