Class: WebammToRails::Sources::Models::AssociationDefinition::Presenter

Inherits:
Object
  • Object
show all
Defined in:
lib/webamm_to_rails/sources/models/association_definition/presenter.rb

Constant Summary collapse

UnknownAssociationType =
Class.new(StandardError)

Instance Method Summary collapse

Constructor Details

#initialize(table_definition:, association:) ⇒ Presenter

Returns a new instance of Presenter.



8
9
10
11
# File 'lib/webamm_to_rails/sources/models/association_definition/presenter.rb', line 8

def initialize(table_definition:, association:)
  @table_definition = table_definition
  @association = association
end

Instance Method Details

#renderObject



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
39
40
41
42
43
44
# File 'lib/webamm_to_rails/sources/models/association_definition/presenter.rb', line 13

def render
  assoc_definition = case @association.type
                      when 'belongs_to'
                        assoc_def = "belongs_to :#{@association.destination.underscore.singularize}"
                        assoc_def << ", optional: true" unless @association.required
                        assoc_def
                      when 'has_one'
                        "has_one :#{@association.destination.underscore.singularize}"
                      when 'has_many'
                        assoc_def = "has_many :#{@association.destination.underscore.pluralize}"
                        assoc_def << ", through: :#{@association.options.through}" if @association.options&.through.present?
                        assoc_def
                      when 'has_many_and_belongs_to_many'
                        "has_and_belongs_to_many :#{@association.destination.underscore.pluralize}"
                      else
                        raise UnknownAssociationType, @association.type
                      end

  if @association.options&.class_name.present?
    assoc_definition << ", class_name: '#{@association.options.class_name}'"
  end

  if @association.options&.foreign_key.present?
    assoc_definition << ", foreign_key: '#{@association.options.foreign_key}'"
  end

  if @association.options&.dependent.present?
    assoc_definition << ", dependent: :#{@association.options.dependent}"
  end

  assoc_definition
end