class Fixably::CreateHasManyRecord

Attributes

collection[R]
record[R]

Public Class Methods

call(record:, collection:) click to toggle source
# File lib/fixably/create_has_many_record.rb, line 5
def self.call(record:, collection:)
  new(record: record, collection: collection).call
end
new(record:, collection:) click to toggle source
# File lib/fixably/create_has_many_record.rb, line 12
def initialize(record:, collection:)
  @record = record
  @collection = collection
end

Public Instance Methods

call() click to toggle source
# File lib/fixably/create_has_many_record.rb, line 17
def call
  can_append!
  save_record
  collection.elements << record
end

Private Instance Methods

can_append!() click to toggle source
# File lib/fixably/create_has_many_record.rb, line 25
def can_append!
  instance_of_resource_class!
  nested_resource!
  parent_recource_known!
  parent_association_known!
  parent_is_persisted!
end
instance_of_resource_class!() click to toggle source
# File lib/fixably/create_has_many_record.rb, line 33
def instance_of_resource_class!
  return if record.instance_of?(collection.resource_class)

  raise(
    TypeError,
    "Appended record must be an instance of " \
    "#{collection.resource_class.name}"
  )
end
nested_resource!() click to toggle source
# File lib/fixably/create_has_many_record.rb, line 43
def nested_resource!
  return if nested_resource?

  raise(
    ArgumentError,
    "Can only appended resources nested one level deep"
  )
end
nested_resource?() click to toggle source
# File lib/fixably/create_has_many_record.rb, line 52
def nested_resource?
  name_parts = record.class.name.split("::")
  name_parts.length.equal?(3)
end
parent_association_known!() click to toggle source
# File lib/fixably/create_has_many_record.rb, line 63
def parent_association_known!
  return if collection.parent_association

  raise "The association to the parent resource has not been set"
end
parent_id_key() click to toggle source
# File lib/fixably/create_has_many_record.rb, line 85
def parent_id_key
  "#{collection.parent_resource.class.name.split("::").last.underscore}_id".
    to_sym
end
parent_is_persisted!() click to toggle source
# File lib/fixably/create_has_many_record.rb, line 69
def parent_is_persisted!
  if !collection.parent_resource.persisted?
    raise "The parent resource has not been been persisted"
  end

  if !collection.parent_resource.id?
    raise "Cannot find an ID for the parent resource"
  end
end
parent_recource_known!() click to toggle source
# File lib/fixably/create_has_many_record.rb, line 57
def parent_recource_known!
  return if collection.parent_resource

  raise "A parent resource has not been set"
end
save_record() click to toggle source
# File lib/fixably/create_has_many_record.rb, line 79
def save_record
  record.parent_association = collection.parent_association
  record.prefix_options[parent_id_key] = collection.parent_resource.id
  record.save!
end