Skip to content

Instantly share code, notes, and snippets.

@daniel-rikowski
Created November 1, 2018 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniel-rikowski/790e07db36a00925f653714f9c66f20c to your computer and use it in GitHub Desktop.
Save daniel-rikowski/790e07db36a00925f653714f9c66f20c to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
class IncludeBelongsTo < Clowne::Declarations::IncludeAssociation
def initialize(name, **options)
@name = name.to_sym
@scope = nil
@options = options
end
def compile(plan)
plan.add_to(:belongs_to, name, self)
end
end
class BelongsToAssociationCloner < Clowne::Adapters::Base::Association
def call(record)
child = association
return record unless child
child_clone = clone_one(child)
record.__send__(:"#{association_name}=", child_clone)
record
end
def clone_record(record)
record.dup
end
end
class BelongsToResolver
class << self
def call(source, record, declaration, params:, **_options)
association_name = declaration.name.to_s
reflection = source.class.reflections[association_name]
if reflection.nil?
raise UnknownAssociation,
"Association #{declaration.name} couldn't be found for #{source.class}"
end
cloner_class = BelongsToAssociationCloner
cloner_class.new(reflection, source, declaration, params).call(record)
record
end
end
end
Clowne::Declarations.add(:include_belongs_to, IncludeBelongsTo)
Clowne::Adapters::ActiveRecord.register_resolver(:belongs_to, BelongsToResolver)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment