Module: ObjectJSONMapper::Associations::ClassMethods

Defined in:
lib/object_json_mapper/associations.rb

Instance Method Summary collapse

Instance Method Details

#has_many(name, options = {}) ⇒ ObjectJSONMapper::Relation<ObjectJSONMapper::Base>

rubocop:disable Style/PredicateName

Examples:

Basic usage

class User < ObjectJSONMapper::Base
  has_many :products
end

User.find(1).products
# GET http://localhost:3000/v1/users/1/products
# => #<ObjectJSONMapper::Relation @collection=[<Product>...]>

With class_name

class User < ObjectJSONMapper::Base
  has_many :things, class_name: :products
end

User.find(1).things
# GET http://localhost:3000/v1/users/1/things
# => #<ObjectJSONMapper::Relation @collection=[<Product>...]>

With endpoint

class User < ObjectJSONMapper::Base
  has_many :products, endpoint: :things
end

User.find(1).products
# GET http://localhost:3000/v1/users/1/things
# => #<ObjectJSONMapper::Relation @collection=[<Product>...]>

With params

class User < ObjectJSONMapper::Base
  has_many :products, params: { status: :active }
end

User.find(1).products
# GET http://localhost:3000/v1/users/1/products?status=active
# => #<ObjectJSONMapper::Relation @collection=[<Product>...]>

Parameters:

  • association_name (Symbol)
  • class_name (Symbol)

Returns:



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/object_json_mapper/associations.rb', line 49

def has_many(name, options = {})
  associations << HasMany.new(name, options)

  define_method(name) do |reload = false|
    cache_name = :"@#{__method__}"

    if instance_variable_defined?(cache_name) && reload == false
      return instance_variable_get(cache_name)
    end

    instance_variable_set(
      cache_name,
      self.class.associations.find(__method__).call(self)
    )
  end
end

#has_one(name, options = {}) ⇒ ObjectJSONMapper::Base Also known as: belongs_to

Examples:

Basic usage

class User < ObjectJSONMapper::Base
  has_one :profile
end

User.find(1).profile
# GET http://localhost:3000/v1/users/1/profile
# => #<ObjectJSONMapper::Base @attributes={...}>

Parameters:

  • association_name (Symbol)

Returns:



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/object_json_mapper/associations.rb', line 77

def has_one(name, options = {})
  associations << HasOne.new(name, options)

  define_method(name) do |reload = false|
    cache_name = :"@#{__method__}"

    if instance_variable_defined?(cache_name) && reload == false
      return instance_variable_get(cache_name)
    end

    instance_variable_set(
      cache_name,
      self.class.associations.find(__method__).call(self)
    )
  end
end