File: context.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 (91 lines) | stat: -rw-r--r-- 1,973 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# frozen_string_literal: true

require "forwardable"

require_relative "configuration"
require_relative "conversions"
require_relative "conversion_target"

module Necromancer
  # A class used by Necromancer to provide user interace
  #
  # @api public
  class Context
    extend Forwardable

    def_delegators :"@conversions", :register

    # Create a context.
    #
    # @api private
    def initialize(&block)
      block.(configuration) if block_given?
      @conversions = Conversions.new(configuration)
      @conversions.load
    end

    # The configuration object.
    #
    # @example
    #   converter = Necromancer.new
    #   converter.configuration.strict = true
    #
    # @return [Necromancer::Configuration]
    #
    # @api public
    def configuration
      @configuration ||= Configuration.new
    end

    # Yields global configuration to a block.
    #
    # @yield [Necromancer::Configuration]
    #
    # @example
    #   converter = Necromancer.new
    #   converter.configure do |config|
    #     config.strict true
    #   end
    #
    # @api public
    def configure
      yield configuration if block_given?
    end

    # Converts the object
    # @param [Object] object
    #   any object to be converted
    #
    # @api public
    def convert(object = ConversionTarget::UndefinedValue, &block)
      ConversionTarget.for(conversions, object, block)
    end

    # Check if this converter can convert source to target
    #
    # @param [Object] source
    #   the source class
    # @param [Object] target
    #   the target class
    #
    # @return [Boolean]
    #
    # @api public
    def can?(source, target)
      !conversions[source, target].nil?
    rescue NoTypeConversionAvailableError
      false
    end

    # Inspect this context
    #
    # @api public
    def inspect
      %(#<#{self.class}@#{object_id} @config=#{configuration}>)
    end

    protected

    attr_reader :conversions
  end # Context
end # Necromancer