Module: Flipper::Typecast
- Defined in:
- lib/flipper/typecast.rb
Constant Summary collapse
- TruthMap =
{ true => true, 1 => true, 'true' => true, '1' => true, }.freeze
Class Method Summary collapse
-
.to_boolean(value) ⇒ Object
Internal: Convert value to a boolean.
-
.to_float(value) ⇒ Object
Internal: Convert value to a float.
-
.to_integer(value) ⇒ Object
Internal: Convert value to an integer.
-
.to_percentage(value) ⇒ Object
Internal: Convert value to a percentage.
-
.to_set(value) ⇒ Object
Internal: Convert value to a set.
Class Method Details
.to_boolean(value) ⇒ Object
Internal: Convert value to a boolean.
Returns true or false.
13 14 15 |
# File 'lib/flipper/typecast.rb', line 13 def self.to_boolean(value) !!TruthMap[value] end |
.to_float(value) ⇒ Object
Internal: Convert value to a float.
Returns a Float representation of the value. Raises ArgumentError if conversion is not possible.
33 34 35 36 37 38 39 |
# File 'lib/flipper/typecast.rb', line 33 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 |
.to_integer(value) ⇒ Object
Internal: Convert value to an integer.
Returns an Integer representation of the value. Raises ArgumentError if conversion is not possible.
21 22 23 24 25 26 27 |
# File 'lib/flipper/typecast.rb', line 21 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 |
.to_percentage(value) ⇒ Object
Internal: Convert value to a percentage.
Returns a Integer or Float representation of the value. Raises ArgumentError if conversion is not possible.
45 46 47 48 49 50 51 |
# File 'lib/flipper/typecast.rb', line 45 def self.to_percentage(value) if value.to_s.include?('.'.freeze) to_float(value) else to_integer(value) end end |
.to_set(value) ⇒ Object
Internal: Convert value to a set.
Returns a Set representation of the value. Raises ArgumentError if conversion is not possible.
57 58 59 60 61 62 63 64 65 66 |
# File 'lib/flipper/typecast.rb', line 57 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 |