Sha256: ec681a835c7848c8d91e2378f500dc0794b0b448d27a74f43610b52735c967b5

Contents?: true

Size: 1.72 KB

Versions: 1

Compression:

Stored size: 1.72 KB

Contents

# frozen_string_literal: true

require "dry-types"
require "json"

module ROM
  # Default namespace with built-in attribute types
  #
  # @api public
  #
  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|
        ::JSON.parse(value.to_s, symbolize_names: symbol_keys)
      rescue ::JSON::ParserError
        value
      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
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rom-6.0.0.alpha1 lib/rom/types.rb