Class: InputTypes
- Inherits:
-
Object
- Object
- InputTypes
- Defined in:
- lib/clino/plugins/input_types.rb
Instance Method Summary collapse
- #convert(type, value) ⇒ Object
- #convert_bool(value = nil) ⇒ Object
- #convert_float(value = nil) ⇒ Object
- #convert_integer(value = nil) ⇒ Object
- #convert_string(value = nil) ⇒ Object
-
#initialize ⇒ InputTypes
constructor
A new instance of InputTypes.
- #register(type, converter) ⇒ Object
Constructor Details
#initialize ⇒ InputTypes
Returns a new instance of InputTypes.
4 5 6 7 8 9 10 |
# File 'lib/clino/plugins/input_types.rb', line 4 def initialize @converters = {} register(:float, method(:convert_float)) register(:integer, method(:convert_integer)) register(:bool, method(:convert_bool)) register(:string, method(:convert_string)) end |
Instance Method Details
#convert(type, value) ⇒ Object
19 20 21 22 23 |
# File 'lib/clino/plugins/input_types.rb', line 19 def convert(type, value) raise ArgumentError, "Invalid type: #{type}, available types: #{@converters.keys}" unless @converters.key?(type) @converters[type].call(value) end |
#convert_bool(value = nil) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/clino/plugins/input_types.rb', line 37 def convert_bool(value = nil) return nil if value.nil? if [true, false].include?(value) value else true_values = %w[true yes 1 t y] falsy_values = %w[false no 0 f n] if true_values.include?(value.downcase) true elsif falsy_values.include?(value.downcase) false else raise ArgumentError, "Invalid boolean value: #{default}" end end end |
#convert_float(value = nil) ⇒ Object
25 26 27 28 29 |
# File 'lib/clino/plugins/input_types.rb', line 25 def convert_float(value = nil) return nil if value.nil? value.to_f end |
#convert_integer(value = nil) ⇒ Object
31 32 33 34 35 |
# File 'lib/clino/plugins/input_types.rb', line 31 def convert_integer(value = nil) return nil if value.nil? value.to_i end |
#convert_string(value = nil) ⇒ Object
55 56 57 58 59 |
# File 'lib/clino/plugins/input_types.rb', line 55 def convert_string(value = nil) return nil if value.nil? value.to_s end |
#register(type, converter) ⇒ Object
12 13 14 15 16 17 |
# File 'lib/clino/plugins/input_types.rb', line 12 def register(type, converter) raise ArgumentError, "Invalid converter" unless converter.respond_to?(:call) raise ArgumentError, "Invalid type" unless type.is_a?(Symbol) @converters[type] = converter end |