File: converter.rb

package info (click to toggle)
ruby-necromancer 0.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 308 kB
  • sloc: ruby: 1,578; sh: 4; makefile: 4
file content (64 lines) | stat: -rw-r--r-- 1,383 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# frozen_string_literal: true

require_relative "configuration"

module Necromancer
  # Abstract converter used internally as a base for other converters
  #
  # @api private
  class Converter
    # Create an abstract converter
    #
    # @param [Object] source
    #   the source object type
    #
    # @param [Object] target
    #   the target object type
    #
    # @api public
    def initialize(source = nil, target = nil)
      @source = source if source
      @target = target if target
      @config ||= Configuration.new
    end

    # Run converter
    #
    # @api private
    def call(*)
      raise NotImplementedError
    end

    # Creates anonymous converter
    #
    # @api private
    def self.create(&block)
      Class.new(self) do
        define_method(:initialize) { |*a| block.(self, *a) }

        define_method(:call) { |value| convert.(value) }
      end.new
    end

    # Fail with conversion type error
    #
    # @param [Object] value
    #   the value that cannot be converted
    #
    # @api private
    def raise_conversion_type(value)
      raise ConversionTypeError, "'#{value}' could not be converted " \
                                 "from `#{source}` into `#{target}`"
    end

    attr_accessor :source

    attr_accessor :target

    attr_accessor :convert

   # protected

    attr_reader :config
  end # Converter
end # Necromancer