-
-
Save daniel-rikowski/790e07db36a00925f653714f9c66f20c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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