Module: NPR::Concern::Relation::ClassMethods

Defined in:
lib/npr/concern/relation.rb

Overview


Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#_has_many_relationsObject




53
54
55
# File 'lib/npr/concern/relation.rb', line 53

def _has_many_relations
  @_has_many_relations ||= []
end

#_has_one_relationsObject



57
58
59
# File 'lib/npr/concern/relation.rb', line 57

def _has_one_relations
  @_has_one_relations ||= []
end

Instance Method Details

#has_many(name, options) ⇒ Object


Define a relationship Similar to ActiveRecord’s has_many

Arguments:

  • name (String) - the name of the relation

  • options (Hash)

    * class_name (Class) - the class for the related objects
    * key (String) - the JSON key that holds this relation
    

Example:

has_many "links", key: "link", class_name: NPR::Entity::Link


29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/npr/concern/relation.rb', line 29

def has_many(name, options)
  relation = build_relation(name, options)

  # Define getter and setter for this attribute
  # Forces the relation into an empty array when
  # it's first accessed.
  attr_writer name
  define_method name do
    instance_variable_get("@#{name}") || instance_variable_set("@#{name}", [])
  end

  _has_many_relations.push relation
end

#has_one(name, options) ⇒ Object




45
46
47
48
49
# File 'lib/npr/concern/relation.rb', line 45

def has_one(name, options)
  relation = build_relation(name, options)
  attr_accessor name
  _has_one_relations.push relation
end