Sha256: 722ab5ef893d2d2cee7dc7948623d62a8fab8250aa3c6be434eabd178f23314a

Contents?: true

Size: 1.92 KB

Versions: 2

Compression:

Stored size: 1.92 KB

Contents

# frozen_string_literal: true

module DirtySeed
  # Represents an Active Record attribute
  class Attribute < SimpleDelegator
    # @!method initialize(column)
    # @param column [ActiveRecord::ConnectionAdapters::Column]
    # @return [DirtySeed::Attribute]

    attr_accessor :model
    attr_writer :validators, :enum

    delegate :value, to: :assigner

    TYPE_SYMMETRY = {
      binary: :integer,
      datetime: :time,
      decimal: :float,
      jsonb: :json,
      text: :string
    }.freeze
    private_constant :TYPE_SYMMETRY

    # Returns the attribute assigner
    # @return [DirtySeed::Assigners::Assigner]
    def assigner
      @assigner ||= DirtySeed::Assigners::Dispatcher.new(self)
    end

    # Returns attribute type
    # @return [Symbol]
    def type
      sql_type = sql_type_metadata.type.to_s.gsub('[]', '').to_sym
      @type ||= TYPE_SYMMETRY[sql_type] || sql_type
    end

    # Is attribute an array?
    # @return [Boolean]
    # @note When attribute is serialized as array, it raises an error
    #   if value is not an array -> use this to define if it is an array
    def array?
      return @array unless @array.nil?
      return true if sql_type_metadata.type.to_s.include? '[]'

      begin
        model&.new(name => '')
        # it does not raise error -> it is not a serialized array
        false
      rescue ActiveRecord::SerializationTypeMismatch
        # it raises an error -> it is (certainly) a serialized array
        true
      rescue StandardError
        # if any other error raises, return false
        false
      end
    end

    # Returns validators
    # @return [Array<Object>] array of validators
    def validators
      @validators ||=
        model&.validators&.select do |validator|
          validator.attributes.include? name.to_sym
        end
    end

    # Returns enum
    # @return [Array<Object>] array of options
    def enum
      @enum ||= model&.defined_enums&.dig(name)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dirty_seed-0.2.1 lib/dirty_seed/attribute.rb
dirty_seed-0.2.0 lib/dirty_seed/attribute.rb