Class: Necromancer::ConversionTarget Private

Inherits:
Object
  • Object
show all
Defined in:
lib/necromancer/conversion_target.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

A class responsible for wrapping conversion target

Constant Summary collapse

UndefinedValue =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Used as a stand in for lack of value

Module.new

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(conversions, object) ⇒ ConversionTarget

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of ConversionTarget.



13
14
15
16
# File 'lib/necromancer/conversion_target.rb', line 13

def initialize(conversions, object)
  @object = object
  @conversions = conversions
end

Class Method Details

.for(context, value, block) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/necromancer/conversion_target.rb', line 19

def self.for(context, value, block)
  if UndefinedValue.equal?(value)
    unless block
      raise ArgumentError,
            "You need to pass either argument or a block to `convert`."
    end
    new(context, block.call)
  elsif block
    raise ArgumentError,
          "You cannot pass both an argument and a block to `convert`."
  else
    new(context, value)
  end
end

Instance Method Details

#from(source) ⇒ ConversionType

Allows to specify conversion source type

Examples:

converter.convert("1").from(:string).to(:numeric)  # => 1

Returns:

  • (ConversionType)


42
43
44
45
# File 'lib/necromancer/conversion_target.rb', line 42

def from(source)
  @source = source
  self
end

#inspectObject

Inspect this conversion



68
69
70
# File 'lib/necromancer/conversion_target.rb', line 68

def inspect
  %(#<#{self.class}@#{object_id} @object=#{object}, @source=#{detect(object)}>)
end

#to(target, options = {}) ⇒ Object Also known as: >>

Runs a given conversion

Examples:

converter.convert("1").to(:numeric)  # => 1
converter.convert("1") >> Integer # => 1

Returns:

  • (Object)

    the converted target type



59
60
61
62
# File 'lib/necromancer/conversion_target.rb', line 59

def to(target, options = {})
  conversion = conversions[source || detect(object, false), detect(target)]
  conversion.call(object, **options)
end