class Necromancer::ConversionTarget

A class responsible for wrapping conversion target

@api private

Constants

UndefinedValue

Used as a stand in for lack of value @api private

Attributes

conversions[R]
object[R]
source[R]

Public Class Methods

for(context, value, block) click to toggle source

@api private

# File lib/necromancer/conversion_target.rb, line 18
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
new(conversions, object) click to toggle source

@api private

# File lib/necromancer/conversion_target.rb, line 12
def initialize(conversions, object)
  @object = object
  @conversions = conversions
end

Public Instance Methods

>>(target, options = {})
Alias for: to
from(source) click to toggle source

Allows to specify conversion source type

@example

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

@return [ConversionType]

@api public

# File lib/necromancer/conversion_target.rb, line 41
def from(source)
  @source = source
  self
end
inspect() click to toggle source

Inspect this conversion

@api public

# File lib/necromancer/conversion_target.rb, line 67
def inspect
  %(#<#{self.class}@#{object_id} @object=#{object}, @source=#{detect(object)}>)
end
to(target, options = {}) click to toggle source

Runs a given conversion

@example

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

@example

converter.convert('1') >> Integer # => 1

@return [Object]

the converted target type

@api public

# File lib/necromancer/conversion_target.rb, line 58
def to(target, options = {})
  conversion = conversions[source || detect(object, false), detect(target)]
  conversion.call(object, options)
end
Also aliased as: >>

Protected Instance Methods

detect(object, symbol_as_object = true) click to toggle source

Detect object type and coerce into known key type

@param [Object] object

@api private

# File lib/necromancer/conversion_target.rb, line 78
def detect(object, symbol_as_object = true)
  case object
  when TrueClass, FalseClass then :boolean
  when Integer then :integer
  when Class   then object.name.downcase
  else
    if object.is_a?(Symbol) && symbol_as_object
      object
    else
      object.class.name.downcase
    end
  end
end