Class: Perron::Relation
- Inherits:
-
Array
- Object
- Array
- Perron::Relation
- Defined in:
- lib/perron/relation.rb
Instance Attribute Summary collapse
-
#model_class ⇒ Object
readonly
Returns the value of attribute model_class.
Instance Method Summary collapse
- #in_order_of(attribute, values, filter: true) ⇒ Object
-
#initialize(resources = [], model_class = nil) ⇒ Relation
constructor
A new instance of Relation.
- #limit(count) ⇒ Object
- #offset(count) ⇒ Object
- #order(attribute, direction = :asc) ⇒ Object
- #pluck(*attributes) ⇒ Object
- #where(**conditions) ⇒ Object
Constructor Details
#initialize(resources = [], model_class = nil) ⇒ Relation
Returns a new instance of Relation.
5 6 7 8 9 |
# File 'lib/perron/relation.rb', line 5 def initialize(resources = [], model_class = nil) super(resources) @model_class = model_class end |
Instance Attribute Details
#model_class ⇒ Object (readonly)
Returns the value of attribute model_class.
10 11 12 |
# File 'lib/perron/relation.rb', line 10 def model_class @model_class end |
Instance Method Details
#in_order_of(attribute, values, filter: true) ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/perron/relation.rb', line 54 def in_order_of(attribute, values, filter: true) return Relation.new([]) if values.empty? indexed = values.each_with_index.to_h resources = if filter select { indexed.key?(it.public_send(attribute)) } .sort_by { indexed[it.public_send(attribute)] } else sort_by { indexed[it.public_send(attribute)] || Float::INFINITY } end Relation.new(resources) end |
#limit(count) ⇒ Object
28 |
# File 'lib/perron/relation.rb', line 28 def limit(count) = Relation.new(first(count), @model_class) |
#offset(count) ⇒ Object
30 |
# File 'lib/perron/relation.rb', line 30 def offset(count) = Relation.new(drop(count), @model_class) |
#order(attribute, direction = :asc) ⇒ Object
32 33 34 35 36 37 38 39 40 |
# File 'lib/perron/relation.rb', line 32 def order(attribute, direction = :asc) if attribute.is_a?(Hash) attribute, direction = attribute.first end sorted = sort_by { it.public_send(attribute) } Relation.new((direction == :desc) ? sorted.reverse : sorted, @model_class) end |
#pluck(*attributes) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/perron/relation.rb', line 42 def pluck(*attributes) raise ArgumentError, "wrong number of arguments (given 0, expected 1+)" if attributes.empty? map do |resource| if attributes.size == 1 resource.public_send(attributes.first) else attributes.map { resource.public_send(it) } end end end |
#where(**conditions) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/perron/relation.rb', line 12 def where(**conditions) filtered = select do |resource| conditions.all? do |key, value| key_value = resource.public_send(key) if value.is_a?(Array) value.map(&:to_s).include?(key_value.to_s) else key_value.to_s == value.to_s end end end Relation.new(filtered, @model_class) end |