Class: JSONAPI::Association

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

Direct Known Subclasses

HasMany, HasOne

Defined Under Namespace

Classes: HasMany, HasOne

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ Association

Returns a new instance of Association.



6
7
8
9
10
11
12
13
14
# File 'lib/jsonapi/association.rb', line 6

def initialize(name, options = {})
  @name = name.to_s
  @options = options
  @acts_as_set = options.fetch(:acts_as_set, false) == true
  @foreign_key = options[:foreign_key] ? options[:foreign_key].to_sym : nil
  @module_path = options[:module_path] || ''
  @relation_name = options.fetch(:relation_name, @name)
  @polymorphic = options.fetch(:polymorphic, false) == true
end

Instance Attribute Details

#acts_as_setObject (readonly)

Returns the value of attribute acts_as_set.



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

def acts_as_set
  @acts_as_set
end

#class_nameObject (readonly)

Returns the value of attribute class_name.



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

def class_name
  @class_name
end

#foreign_keyObject (readonly)

Returns the value of attribute foreign_key.



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

def foreign_key
  @foreign_key
end

#nameObject (readonly)

Returns the value of attribute name.



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

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



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

def options
  @options
end

#polymorphicObject (readonly) Also known as: polymorphic?

Returns the value of attribute polymorphic.



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

def polymorphic
  @polymorphic
end

#typeObject (readonly)

Returns the value of attribute type.



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

def type
  @type
end

Instance Method Details

#primary_keyObject



18
19
20
# File 'lib/jsonapi/association.rb', line 18

def primary_key
  @primary_key ||= resource_klass._primary_key
end

#relation_name(options = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/jsonapi/association.rb', line 26

def relation_name(options = {})
  case @relation_name
    when Symbol
      # :nocov:
      @relation_name
      # :nocov:
    when String
      @relation_name.to_sym
    when Proc
      @relation_name.call(options)
  end
end

#resource_klassObject



22
23
24
# File 'lib/jsonapi/association.rb', line 22

def resource_klass
  @resource_klass ||= Resource.resource_for(@module_path + @class_name)
end

#type_for_source(source) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/jsonapi/association.rb', line 39

def type_for_source(source)
  if polymorphic?
    resource = source.public_send(name)
    resource.class._type if resource
  else
    type
  end
end