Module: JsonApiClient::Helpers::Associatable::ClassMethods

Defined in:
lib/json_api_client/helpers/associatable.rb

Instance Method Summary collapse

Instance Method Details

#_define_association(attr_name, association_klass, options = {}) ⇒ Object



14
15
16
17
18
# File 'lib/json_api_client/helpers/associatable.rb', line 14

def _define_association(attr_name, association_klass, options = {})
  attr_name = attr_name.to_sym
  association = association_klass.new(attr_name, self, options)
  self.associations += [association]
end

#_define_relationship_methods(attr_name) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/json_api_client/helpers/associatable.rb', line 20

def _define_relationship_methods(attr_name)
  attr_name = attr_name.to_sym

  define_method(attr_name) do
    _cached_relationship(attr_name) do
      relationship_definition = relationship_definition_for(attr_name)
      return unless relationship_definition
      relationship_data_for(attr_name, relationship_definition)
    end
  end

  define_method("#{attr_name}=") do |value|
    _clear_cached_relationship(attr_name)
    relationships.public_send("#{attr_name}=", value)
  end
end

#belongs_to(attr_name, options = {}) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/json_api_client/helpers/associatable.rb', line 37

def belongs_to(attr_name, options = {})
  _define_association(attr_name, JsonApiClient::Associations::BelongsTo::Association, options)

  param = associations.last.param
  define_method(param) do
    _belongs_to_params[param]
  end

  define_method(:"#{param}=") do |value|
    _belongs_to_params[param] = value
  end
end

#has_many(attr_name, options = {}) ⇒ Object



50
51
52
53
# File 'lib/json_api_client/helpers/associatable.rb', line 50

def has_many(attr_name, options = {})
  _define_association(attr_name, JsonApiClient::Associations::HasMany::Association, options)
  _define_relationship_methods(attr_name)
end

#has_one(attr_name, options = {}) ⇒ Object



55
56
57
58
# File 'lib/json_api_client/helpers/associatable.rb', line 55

def has_one(attr_name, options = {})
  _define_association(attr_name, JsonApiClient::Associations::HasOne::Association, options)
  _define_relationship_methods(attr_name)
end