Sha256: 355a8fe0852ae68d37749497904ed4464d6f703f0eb82411e355610eb4f06152

Contents?: true

Size: 1.34 KB

Versions: 6

Compression:

Stored size: 1.34 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)) if builder
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rom-core-5.1.2 lib/rom/mapper/model_dsl.rb
rom-core-5.1.1 lib/rom/mapper/model_dsl.rb
rom-core-5.1.0 lib/rom/mapper/model_dsl.rb
rom-core-5.0.2 lib/rom/mapper/model_dsl.rb
rom-core-5.0.1 lib/rom/mapper/model_dsl.rb
rom-core-5.0.0 lib/rom/mapper/model_dsl.rb