Class: Traits::List

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/traits/list.rb

Instance Method Summary collapse

Constructor Details

#initialize(list = []) ⇒ List

Returns a new instance of List.



5
6
7
# File 'lib/traits/list.rb', line 5

def initialize(list = [])
  @list = list
end

Instance Method Details

#[](arg) ⇒ Object



35
36
37
# File 'lib/traits/list.rb', line 35

def [](arg)
  by_name(arg)
end

#by_name(name) ⇒ Object



43
44
45
46
# File 'lib/traits/list.rb', line 43

def by_name(name)
  name = name.to_s.to_sym
  find { |attr| attr.name == name }
end

#each(&block) ⇒ Object



39
40
41
# File 'lib/traits/list.rb', line 39

def each(&block)
  @list.each(&block)
end

#filter(hash) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/traits/list.rb', line 9

def filter(hash)
  select do |attr|
    hash.all? do |method, expected|
      returned = attr.send(method)
      if expected.is_a?(Array)
        expected.include?(returned)
      else
        returned == expected
      end
    end
  end
end

#first_where(hash) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/traits/list.rb', line 22

def first_where(hash)
  find do |attr|
    hash.all? do |method, expected|
      returned = attr.send(method)
      if expected.is_a?(Array)
        expected.include?(returned)
      else
        returned == expected
      end
    end
  end
end

#to_hashObject



48
49
50
# File 'lib/traits/list.rb', line 48

def to_hash
  each_with_object({}) { |item, memo| memo[item.name] = item.to_hash }
end