Sha256: 9d89580df10dce90b7bb90e73bbc76c0e179ae293ca5fafe71b59f193b2594ed

Contents?: true

Size: 1.87 KB

Versions: 4

Compression:

Stored size: 1.87 KB

Contents

# frozen_string_literal: true

module AnnotateRb
  module ModelAnnotator
    module ColumnAnnotation
      class AnnotationBuilder
        def initialize(column, model, max_size, options)
          @column = column
          @model = model
          @max_size = max_size
          @options = options
        end

        def build
          is_primary_key = is_column_primary_key?(@model, @column.name)

          table_indices = @model.retrieve_indexes_from_table
          column_indices = table_indices.select { |ind| ind.columns.include?(@column.name) }
          column_defaults = @model.column_defaults

          column_attributes = AttributesBuilder.new(@column, @options, is_primary_key, column_indices, column_defaults).build
          formatted_column_type = TypeBuilder.new(@column, @options, column_defaults).build

          display_column_comments = @options[:with_comment] && @options[:with_column_comments]
          col_name = if display_column_comments && @model.with_comments? && @column.comment
            "#{@column.name}(#{@column.comment.gsub(/\n/, '\\n')})"
          else
            @column.name
          end

          _component = ColumnComponent.new(col_name, @max_size, formatted_column_type, column_attributes)
        end

        private

        # TODO: Simplify this conditional
        def is_column_primary_key?(model, column_name)
          if model.primary_key
            if model.primary_key.is_a?(Array)
              # If the model has multiple primary keys, check if this column is one of them
              if model.primary_key.collect(&:to_sym).include?(column_name.to_sym)
                return true
              end
            elsif column_name.to_sym == model.primary_key.to_sym
              # If model has 1 primary key, check if this column is it
              return true
            end
          end

          false
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
annotaterb-4.13.0 lib/annotate_rb/model_annotator/column_annotation/annotation_builder.rb
annotaterb-4.12.0 lib/annotate_rb/model_annotator/column_annotation/annotation_builder.rb
annotaterb-4.11.0 lib/annotate_rb/model_annotator/column_annotation/annotation_builder.rb
annotaterb-4.10.2 lib/annotate_rb/model_annotator/column_annotation/annotation_builder.rb