Class: RelationToJSON::ReflectionBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/relation_to_json/reflection_builder.rb

Defined Under Namespace

Classes: UnsupportedReflectionType

Class Method Summary collapse

Class Method Details

.build(schema_associations, relation) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/relation_to_json/reflection_builder.rb', line 15

def self.build(schema_associations, relation)
  schema_associations.to_h do |reflection_name, reflection_columns|
    # for each association
    # we first have to get the relation that the association has
    # with the active record relation
    active_record_reflection = relation.model.reflections.fetch(reflection_name.to_s)

    klass = case active_record_reflection
    when ActiveRecord::Reflection::BelongsToReflection
      RelationToJSON::BelongsToReflection
    when ActiveRecord::Reflection::HasOneReflection
      RelationToJSON::HasOneReflection
    else
      raise UnsupportedReflectionType.new(active_record_reflection)
    end

    [
      reflection_name,
      klass.new(active_record_reflection, reflection_name, reflection_columns),
    ]
  end
end