Class: LocalModel::Collection

Inherits:
Array
  • Object
show all
Defined in:
lib/local_model/collection.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#add_to_collectionObject

Returns the value of attribute add_to_collection.



11
12
13
# File 'lib/local_model/collection.rb', line 11

def add_to_collection
  @add_to_collection
end

#collection_classObject

Returns the value of attribute collection_class.



11
12
13
# File 'lib/local_model/collection.rb', line 11

def collection_class
  @collection_class
end

#modelObject

Returns the value of attribute model.



11
12
13
# File 'lib/local_model/collection.rb', line 11

def model
  @model
end

Class Method Details

.create_from(array:, for_model:, for_collection_class:, add_to_collection_proc:) ⇒ Object



3
4
5
6
7
8
9
# File 'lib/local_model/collection.rb', line 3

def self.create_from(array: , for_model: , for_collection_class:, add_to_collection_proc:)
   new_obj = new(array)
   new_obj.model = for_model 
   new_obj.collection_class = for_collection_class
   new_obj.add_to_collection = add_to_collection_proc
   new_obj
end

Instance Method Details

#<<(arg) ⇒ Object



13
14
15
# File 'lib/local_model/collection.rb', line 13

def <<(arg)
    self.push(arg)
end

#build(**args) ⇒ Object



24
25
26
# File 'lib/local_model/collection.rb', line 24

def build(**args)
    self.push(collection_class.create(**args))
end

#find_by(**args) ⇒ Object



47
48
49
# File 'lib/local_model/collection.rb', line 47

def find_by(**args)
    where(**args).first
end

#firstObject



51
52
53
# File 'lib/local_model/collection.rb', line 51

def first
    self[0]
end

#lastObject



55
56
57
# File 'lib/local_model/collection.rb', line 55

def last
    self[-1]
end

#push(arg) ⇒ Object

Raises:

  • (ArgumentError)


17
18
19
20
21
22
# File 'lib/local_model/collection.rb', line 17

def push(arg)
    self.[]=(self.length, arg)
    raise ArgumentError.new("#{arg.class} inputted, expecting #{self.collection_class}") if !arg.is_a?(self.collection_class)
    add_to_collection[arg, self.model]
    arg.save && self.model.save
end

#where(**args) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/local_model/collection.rb', line 28

def where(**args)
    arr = self.filter do |el|
        found = true
        args.each do |k,v|
            if el.send(k.to_s) != v
                found = false
                break
            end
        end
        found
    end
    self.class.create_from(
        array: arr,
        for_model: model,
        for_collection_class: nil,
        add_to_collection_proc: ->(a,b) { raise NoMethodError.new("Cannot add to this collection") }
    )
end