Module: OceanDynamo::BelongsTo

Included in:
Table
Defined in:
lib/ocean-dynamo/associations/belongs_to.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
# File 'lib/ocean-dynamo/associations/belongs_to.rb', line 4

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#load_target_from_id(name, composite_key) ⇒ Object

:nodoc:



188
189
190
191
192
193
# File 'lib/ocean-dynamo/associations/belongs_to.rb', line 188

def load_target_from_id(name, composite_key)  # :nodoc:
  v = read_attribute(name)
  return nil unless v
  h, r = composite_key ? v.split(':') : v
  fields[name][:target_class].find(h, r, consistent: true)
end

#set_belongs_to_association(attrs) ⇒ Object

This is run by #initialize and by #assign_attributes to set the association instance variables (@master, for instance) and their associated attributes (such as master_id) from one single given value such as :master and :master_id.



180
181
182
183
184
185
# File 'lib/ocean-dynamo/associations/belongs_to.rb', line 180

def set_belongs_to_association(attrs)  # :nodoc:
  parent_class = self.class.belongs_to_class
  return unless parent_class
  parent_class = parent_class.to_s.underscore.to_sym
  send("#{parent_class}=", attrs[parent_class]) if attrs && attrs.include?(parent_class)
end

#type_check_foreign_key(name, value) ⇒ Object



196
197
198
199
200
# File 'lib/ocean-dynamo/associations/belongs_to.rb', line 196

def type_check_foreign_key(name, value)
  return unless value
  return if value.is_a?(String)
  raise AssociationTypeMismatch, "Foreign key #{name} must be nil or a string"
end

#type_check_target(target_class, value, composite_key) ⇒ Object



203
204
205
206
207
208
209
210
211
212
# File 'lib/ocean-dynamo/associations/belongs_to.rb', line 203

def type_check_target(target_class, value, composite_key)
  return nil unless value
  if value.kind_of?(target_class)
    foreign_key = value.hash_key
    foreign_key += ':' + value.range_key if composite_key
    return [value, foreign_key]
  else
    raise AssociationTypeMismatch, "can't save a #{value.class} in a #{target_class} foreign key"
  end
end