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



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/json_api_client/helpers/associatable.rb', line 13

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]

  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



32
33
34
# File 'lib/json_api_client/helpers/associatable.rb', line 32

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

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



36
37
38
# File 'lib/json_api_client/helpers/associatable.rb', line 36

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

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



40
41
42
# File 'lib/json_api_client/helpers/associatable.rb', line 40

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