Module: SciYAG::Backends::Descriptions::Conversion
- Included in:
- Parameter
- Defined in:
- lib/SciYAG/Backends/descriptions.rb
Overview
A module to convert text input into an object of the given type.
Constant Summary collapse
- TRUE_RE =
The regular expression that matches ‘true’ for boolean values:
/^\s*(true|yes)\s*$/i
- FALSE_RE =
The regular expression that matches ‘false’
/^\s*(false|no(ne)?)\s*$/i
Instance Method Summary collapse
-
#text_to_type(text, type) ⇒ Object
Converts
text
to the given type.
Instance Method Details
#text_to_type(text, type) ⇒ Object
Converts text
to the given type. It support different schemes:
-
if
type
is String, Float, Array of Integer, the values are converted using the appropriate functions; -
if
type
is a string, the type is considered to be String; this leaves a possibility to implement a more precise mechanism for choosing; see Descriptions::Parameter#type -
if
type
is :bool, the text is interpreted as a true/false expression. -
if
type
is an array (of symbols/strings), then a valid input is one of the elements of the arrays (it is converted to symbols if necessary) -
if
type
is a hash, it behaves as if the keys had been specified as an array. The values can be used to provide a proper name; -
for any other input,
type
is assumed to be a class, and its constructor should support build from 1 argument, a String.
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 |
# File 'lib/SciYAG/Backends/descriptions.rb', line 51 def text_to_type(text, type) # warning: case cannot be used, as it is the comparison # === which is used, that is is_a?. if type == String value = String(text) elsif type.is_a?(String) # some special specification; # always a string value = String(text) elsif type == Float value = Float(text) elsif type == Array value = Array(text) elsif type == Integer value = Integer(text) elsif type.is_a?(Array) h = {} type.each do |a| h[a.to_s] = a end return h[text] # No checking done... elsif type.is_a?(Hash) return text_to_type(text, type.keys) elsif type == :bool if text =~ TRUE_RE return true else return false end else value = type.new(text) end return value end |