Class: Perron::Relation

Inherits:
Array
  • Object
show all
Defined in:
lib/perron/relation.rb

Instance Method Summary collapse

Constructor Details

#initialize(resources = []) ⇒ Relation

Returns a new instance of Relation.



5
6
7
# File 'lib/perron/relation.rb', line 5

def initialize(resources = [])
  super
end

Instance Method Details

#limit(count) ⇒ Object



25
# File 'lib/perron/relation.rb', line 25

def limit(count) = Relation.new(first(count))

#offset(count) ⇒ Object



27
# File 'lib/perron/relation.rb', line 27

def offset(count) = Relation.new(drop(count))

#order(attribute, direction = :asc) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/perron/relation.rb', line 29

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)
end

#pluck(*attributes) ⇒ Object

Raises:

  • (ArgumentError)


39
40
41
42
43
44
45
46
47
48
49
# File 'lib/perron/relation.rb', line 39

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



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/perron/relation.rb', line 9

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)
end