Sha256: d289f182c61b4431708501982ee244b5fdbe0d99e4f90e4ed1c8f6111890b77c

Contents?: true

Size: 1.67 KB

Versions: 1

Compression:

Stored size: 1.67 KB

Contents

# frozen_string_literal: true

module Orthoses
  module ActiveModel
    # < 7.0
    #   def attribute(name, type = Type::Value.new, **options)
    # >= 7.0
    #   def attribute(name, cast_type = nil, default: NO_DEFAULT_PROVIDED, **options)
    class Attributes
      DEFAULT_TYPES = {
        big_integer: '::Integer',
        binary: '::String',
        boolean: 'bool',
        date: '::Date',
        datetime: '::Time',
        decimal: '::BigDecimal',
        float: '::Float',
        immutable_string: '::String',
        integer: '::Integer',
        string: '::String',
        time: '::Time'
      }

      def initialize(loader)
        @loader = loader
      end

      def call
        attribute = CallTracer::Lazy.new
        store = attribute.trace('ActiveModel::Attributes::ClassMethods#attribute') do
          @loader.call
        end
        attribute.captures.each do |capture|
          receiver_name = Utils.module_name(capture.method.receiver) or next
          name = capture.argument[:name]
          cast_type = capture.argument[:cast_type] || capture.argument[:type]

          return_type = DEFAULT_TYPES[cast_type] || 'untyped'

          generated_attribute_methods = "#{receiver_name}::ActiveModelGeneratedAttributeMethods"
          c = store[generated_attribute_methods]
          c.header = "module #{generated_attribute_methods}"
          c << "def #{name}: () -> #{return_type}?"
          c << "def #{name}=: (untyped) -> untyped"

          unless store[receiver_name].body.include?("include #{generated_attribute_methods}")
            store[receiver_name] << "include #{generated_attribute_methods}"
          end
        end

        store
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
orthoses-rails-1.3.0 lib/orthoses/active_model/attributes.rb