Class: Orthoses::ActiveRecord::HasOne

Inherits:
Object
  • Object
show all
Defined in:
lib/orthoses/active_record/has_one.rb

Instance Method Summary collapse

Constructor Details

#initialize(loader) ⇒ HasOne

Returns a new instance of HasOne.



6
7
8
# File 'lib/orthoses/active_record/has_one.rb', line 6

def initialize(loader)
  @loader = loader
end

Instance Method Details

#callObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/orthoses/active_record/has_one.rb', line 10

def call
  @loader.call.tap do |store|
    ::ActiveRecord::Base.descendants.each do |base|
      next if base.abstract_class?
      base_name = Utils.module_name(base) || next

      lines = base.reflect_on_all_associations(:has_one).flat_map do |ref|
        type = Orthoses::ActiveRecord.reflection_klass_name(ref) or next
        opt = "#{type}?"

        [
          "def #{ref.name}: () -> #{opt}",
          "def #{ref.name}=: (#{opt}) -> #{opt}",
          "def build_#{ref.name}: (?untyped attributes) ?{ (#{type}) -> void } -> #{type}",
          "def create_#{ref.name}: (?untyped attributes) ?{ (#{type}) -> void } -> #{type}",
          "def create_#{ref.name}!: (?untyped attributes) ?{ (#{type}) -> void } -> #{type}",
          "def reload_#{ref.name}: () -> #{opt}",
        ]
      end

      generated_association_methods = "#{base_name}::GeneratedAssociationMethods"
      store[generated_association_methods].header = "module #{generated_association_methods}"
      store[generated_association_methods].concat(lines)

      sig = "include #{generated_association_methods}"
      store[base_name] << sig if !store[base_name].body.include?(sig)
    end
  end
end