Class: ActiveRecord::SortableBy::Field
- Inherits:
-
Object
- Object
- ActiveRecord::SortableBy::Field
- Defined in:
- lib/sortable_by.rb
Overview
:nodoc:
Instance Method Summary collapse
-
#initialize(name, opts = {}) ⇒ Field
constructor
A new instance of Field.
- #order(relation, rank) ⇒ Object
Constructor Details
#initialize(name, opts = {}) ⇒ Field
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/sortable_by.rb', line 63 def initialize(name, opts = {}) @cols = Array.wrap(opts[:as]) @eager_load = Array.wrap(opts[:eager_load]).presence # validate custom_scope @custom_scope = opts[:scope] if @custom_scope && !@custom_scope.is_a?(Proc) raise ArgumentError, "Invalid sortable-by field '#{name}': scope must be a Proc." end # normalize cols @cols.push name if @cols.empty? @cols.each do |col| case col when String, Symbol, Arel::Attributes::Attribute, Arel::Nodes::Node next when Proc unless col.arity == 2 raise ArgumentError, "Invalid sortable-by field '#{name}': proc must accept 2 arguments." end else raise ArgumentError, "Invalid sortable-by field '#{name}': invalid type #{col.class}." end end end |
Instance Method Details
#order(relation, rank) ⇒ Object
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/sortable_by.rb', line 89 def order(relation, rank) @cols.each do |col| case col when String, Symbol relation = relation.order(col => rank) when Arel::Nodes::Node, Arel::Attributes::Attribute relation = relation.order(col.send(rank)) when Proc relation = col.call(relation, rank) end end relation = relation.eager_load(*@eager_load) if @eager_load relation = relation.instance_eval(&@custom_scope) if @custom_scope relation end |