class Naseweis::Converter
The Converter
class provides a way to convert between stringy data and native Ruby types. It's used to handle the type:
attribute of questions.
@attr_reader [Hash] converters A hash of all available types.
Attributes
converters[R]
Public Class Methods
new()
click to toggle source
# File lib/naseweis/converter.rb, line 35 def initialize @converters = { int: ->(x) { Integer x }, integer: ->(x) { Integer x }, regex: ->(x) { Regexp.new x }, regexp: ->(x) { Regexp.new x }, float: ->(x) { Float x }, } end
Public Instance Methods
convert(data, type)
click to toggle source
Convert the data to the given target type
@param data [String] the question answer @param type [String] the target type @return [Object] the converted data @raise [ConversionError] if the data cannot be converted to the given
target
# File lib/naseweis/converter.rb, line 52 def convert(data, type) type = type.intern raise ArgumentError, "Invalid type #{type}" unless @converters.key? type begin @converters[type][data] rescue raise ConversionError.new data, type end end
supported_types()
click to toggle source
Get a list of all supported types
@return [Array] an array of supported types
# File lib/naseweis/converter.rb, line 65 def supported_types @converters.keys end