Sha256: db5fcea6dd5e2607c6b85a12fc7f88a5bfa4e6014eecbf64a79ba42ed2948120

Contents?: true

Size: 1.1 KB

Versions: 12

Compression:

Stored size: 1.1 KB

Contents

# frozen_string_literal: true

require 'luna_park/errors'

module LunaPark
  module Extensions
    ##
    # class-level mixin
    #
    # @example
    #  class Account
    #    extend LunaPark::Extensions::Wrappable
    #
    #    attr_reader :type, :id
    #
    #    def initialize(type:, id:)
    #      @type, @id = type, id
    #    end
    #  end
    #
    #  hash = { type: 'user', id: 42 }
    #  acccount = Account.new(hash)
    #
    #  Account.new(hash)      # => #<Account type='user', id=42>
    #  Account.new(acccount)  # => raise ArgumentError
    #  Account.wrap(hash)     # => #<Account type='user', id=42>
    #  Account.wrap(acccount) # => #<Account type='user', id=42>
    #  Account.wrap(nil)      # => nil
    #  Account.wrap(true)     # => raise 'Account can not wrap TrueClass'
    #
    #  Account.wrap(account).eql?(account) # => true
    module Wrappable
      def wrap(input)
        case input
        when self then input
        when Hash then new(input)
        when nil  then nil
        else raise Errors::Unwrapable, "#{self} can not wrap #{input.class}"
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
luna_park-0.13.1 lib/luna_park/extensions/wrappable.rb
luna_park-0.13.0 lib/luna_park/extensions/wrappable.rb
luna_park-0.12.1 lib/luna_park/extensions/wrappable.rb
luna_park-0.12.0 lib/luna_park/extensions/wrappable.rb
luna_park-0.11.7 lib/luna_park/extensions/wrappable.rb
luna_park-0.11.6 lib/luna_park/extensions/wrappable.rb
luna_park-0.11.5 lib/luna_park/extensions/wrappable.rb
luna_park-0.11.4 lib/luna_park/extensions/wrappable.rb
luna_park-0.11.3 lib/luna_park/extensions/wrappable.rb
luna_park-0.11.2 lib/luna_park/extensions/wrappable.rb
luna_park-0.11.1 lib/luna_park/extensions/wrappable.rb
luna_park-0.11.0 lib/luna_park/extensions/wrappable.rb