Sha256: ad66cee5a5276742f651d81fdff14c42447017fecf2bac05c92ca75f3532c531

Contents?: true

Size: 1.83 KB

Versions: 15

Compression:

Stored size: 1.83 KB

Contents

# frozen_string_literal: true

require 'dry-types'
require 'json'

module ROM
  # Default namespace with built-in attribute types
  #
  # @api public
  #
  # rubocop:disable Naming/MethodName
  module Types
    include Dry::Types(default: :nominal)

    # @api private
    def self.included(other)
      other.extend(Methods)
      super
    end

    # Type extensions
    #
    # @api public
    module Methods
      # Shortcut for defining a foreign key attribute type
      #
      # @param [Symbol] relation The name of the target relation
      # @param [Object] type The type of an attribute
      #
      # @return [Dry::Types::Nominal]
      #
      # @api public
      def ForeignKey(relation, type = Types::Integer)
        type.meta(foreign_key: true, target: relation)
      end
    end

    # @!parse module Coercible;end

    # Define a json-to-hash attribute type
    #
    # @return [Dry::Types::Constructor]
    #
    # @api public
    def Coercible.JSONHash(symbol_keys: false, type: Types::Hash)
      Types.Constructor(type) do |value|
        begin
          ::JSON.parse(value.to_s, symbolize_names: symbol_keys)
        rescue ::JSON::ParserError
          value
        end
      end
    end

    # Define a hash-to-json attribute type
    #
    # @return [Dry::Types::Constructor]
    #
    # @api public
    def Coercible.HashJSON(type: Types::String)
      Types.Constructor(type) { |value| ::JSON.dump(value) }
    end

    # Define a json type with json-to-hash read type
    #
    # @return [Dry::Types::Constructor]
    #
    # @api public
    def Coercible.JSON(symbol_keys: false)
      self.HashJSON.meta(read: self.JSONHash(symbol_keys: symbol_keys))
    end

    Coercible::JSON = Coercible.JSON
    Coercible::JSONHash = Coercible.JSONHash
    Coercible::HashJSON = Coercible.HashJSON
  end
  # rubocop:enable Naming/MethodName
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
rom-core-5.3.2 lib/rom/types.rb
rom-core-5.3.1 lib/rom/types.rb
rom-core-5.3.0 lib/rom/types.rb
rom-core-5.2.6 lib/rom/types.rb
rom-core-5.2.5 lib/rom/types.rb
rom-core-5.2.4 lib/rom/types.rb
rom-core-5.2.3 lib/rom/types.rb
rom-core-5.2.2 lib/rom/types.rb
rom-core-5.2.1 lib/rom/types.rb
rom-core-5.1.2 lib/rom/types.rb
rom-core-5.1.1 lib/rom/types.rb
rom-core-5.1.0 lib/rom/types.rb
rom-core-5.0.2 lib/rom/types.rb
rom-core-5.0.1 lib/rom/types.rb
rom-core-5.0.0 lib/rom/types.rb