Class: Pocus::Association

Inherits:
Array
  • Object
show all
Defined in:
lib/pocus/association.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(owner, name, options) ⇒ Association

Returns a new instance of Association.



5
6
7
8
9
# File 'lib/pocus/association.rb', line 5

def initialize(owner, name, options)
  @owner = owner
  @path = options[:path] || "/#{name}"
  @klass = Object.const_get('Pocus::'.concat(options[:class] || camelize(name)))
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



3
4
5
# File 'lib/pocus/association.rb', line 3

def klass
  @klass
end

#ownerObject (readonly)

Returns the value of attribute owner.



3
4
5
# File 'lib/pocus/association.rb', line 3

def owner
  @owner
end

#pathObject (readonly)

Returns the value of attribute path.



3
4
5
# File 'lib/pocus/association.rb', line 3

def path
  @path
end

Instance Method Details

#allObject



11
12
13
# File 'lib/pocus/association.rb', line 11

def all
  @all ||= owner.get_multiple(path, klass)
end

#create(fields_multiple) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/pocus/association.rb', line 15

def create(fields_multiple)
  if fields_multiple.is_a?(Array)
    owner.post_multiple(path, klass, fields_multiple)
  else
    response = owner.post_multiple(path, klass, [fields_multiple])
    return response if response.empty?
    resource = response.first
    resource.assign_attributes(errors: response.errors || [], warnings: response.warnings || [])
    resource
  end
end

#find(id) ⇒ Object



27
28
29
# File 'lib/pocus/association.rb', line 27

def find(id)
  owner.get("#{path}/#{id}", klass)
end

#find_or_create_by(attributes) ⇒ Object



31
32
33
# File 'lib/pocus/association.rb', line 31

def find_or_create_by(attributes)
  where(attributes).first || create(attributes)
end

#where(filters) ⇒ Object



35
36
37
# File 'lib/pocus/association.rb', line 35

def where(filters)
  owner.get_multiple(path, klass, filters)
end