File: define_explicit_conversions.rb

package info (click to toggle)
ruby-naught 2.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 180 kB
  • sloc: ruby: 658; makefile: 6
file content (31 lines) | stat: -rw-r--r-- 823 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
require "naught/null_class_builder/command"

module Naught
  class NullClassBuilder
    module Commands
      # Adds explicit conversion methods delegating to nil
      #
      # These methods return the same values that nil returns:
      # - to_a => []
      # - to_c => (0+0i)
      # - to_f => 0.0
      # - to_h => {}
      # - to_i => 0
      # - to_r => (0/1)
      # - to_s => ""
      #
      # @api private
      class DefineExplicitConversions < Command
        METHODS = %i[to_a to_c to_f to_h to_i to_r to_s].freeze
        private_constant :METHODS

        # Install explicit conversion methods
        # @return [void]
        # @api private
        def call
          defer { |subject| METHODS.each { |name| subject.define_method(name) { nil.public_send(name) } } }
        end
      end
    end
  end
end