Sha256: 1a553db91e9ca334769ce63f6cf341a4a22d828d31f47d57ff7db62b4eff3c57

Contents?: true

Size: 1.33 KB

Versions: 9

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

require 'rom/model_builder'

module ROM
  class Mapper
    # Model DSL allows setting a model class
    #
    # @private
    module ModelDSL
      attr_reader :attributes, :builder, :klass

      DEFAULT_TYPE = :poro

      # Set or generate a model
      #
      # @example
      #   class MyDefinition
      #     include ROM::Mapper::ModelDSL
      #
      #     def initialize
      #       @attributes = [[:name], [:title]]
      #     end
      #   end
      #
      #   definition = MyDefinition.new
      #
      #   # just set a model constant
      #   definition.model(User)
      #
      #   # generate model class for the attributes
      #   definition.model(name: 'User')
      #
      # @api public
      def model(options = nil)
        if options.is_a?(Class)
          @klass = options
        elsif options
          type = options.fetch(:type) { DEFAULT_TYPE }
          @builder = ModelBuilder[type].new(options)
        end

        build_class unless options
      end

      private

      # Build a model class using a specialized builder
      #
      # @api private
      def build_class
        return klass if klass

        included_attrs = attributes.reject do |_name, opts|
          opts && opts[:exclude]
        end
        builder&.call(included_attrs.map(&:first))
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
rom-core-5.3.2 lib/rom/mapper/model_dsl.rb
rom-core-5.3.1 lib/rom/mapper/model_dsl.rb
rom-core-5.3.0 lib/rom/mapper/model_dsl.rb
rom-core-5.2.6 lib/rom/mapper/model_dsl.rb
rom-core-5.2.5 lib/rom/mapper/model_dsl.rb
rom-core-5.2.4 lib/rom/mapper/model_dsl.rb
rom-core-5.2.3 lib/rom/mapper/model_dsl.rb
rom-core-5.2.2 lib/rom/mapper/model_dsl.rb
rom-core-5.2.1 lib/rom/mapper/model_dsl.rb