File: typecast.rb

package info (click to toggle)
ruby-flipper 0.17.1-6
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 4,896 kB
  • sloc: ruby: 13,876; sh: 55; makefile: 14
file content (70 lines) | stat: -rw-r--r-- 1,793 bytes parent folder | download | duplicates (2)
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
require 'set'

module Flipper
  module Typecast
    TruthMap = {
      true    => true,
      1       => true,
      'true'  => true,
      '1'     => true,
    }.freeze

    # Internal: Convert value to a boolean.
    #
    # Returns true or false.
    def self.to_boolean(value)
      !!TruthMap[value]
    end

    # Internal: Convert value to an integer.
    #
    # Returns an Integer representation of the value.
    # Raises ArgumentError if conversion is not possible.
    def self.to_integer(value)
      if value.respond_to?(:to_i)
        value.to_i
      else
        raise ArgumentError, "#{value.inspect} cannot be converted to an integer"
      end
    end

    # Internal: Convert value to a float.
    #
    # Returns a Float representation of the value.
    # Raises ArgumentError if conversion is not possible.
    def self.to_float(value)
      if value.respond_to?(:to_f)
        value.to_f
      else
        raise ArgumentError, "#{value.inspect} cannot be converted to a float"
      end
    end

    # Internal: Convert value to a percentage.
    #
    # Returns a Integer or Float representation of the value.
    # Raises ArgumentError if conversion is not possible.
    def self.to_percentage(value)
      if value.to_s.include?('.'.freeze)
        to_float(value)
      else
        to_integer(value)
      end
    end

    # Internal: Convert value to a set.
    #
    # Returns a Set representation of the value.
    # Raises ArgumentError if conversion is not possible.
    def self.to_set(value)
      return value if value.is_a?(Set)
      return Set.new if value.nil? || value.empty?

      if value.respond_to?(:to_set)
        value.to_set
      else
        raise ArgumentError, "#{value.inspect} cannot be converted to a set"
      end
    end
  end
end