Module: Xqsr3::Conversion::BoolParser
- Defined in:
- lib/xqsr3/conversion/bool_parser.rb
Overview
+include-able module that provides Boolean parsing
Constant Summary collapse
- DEFAULT_TRUE_VALUES =
Recognised truey values (whole-string match)
[ /\Atrue\z/i, '1' ]
- DEFAULT_FALSE_VALUES =
Recognised falsey values (whole-string match)
[ /\Afalse\z/i, '0' ]
Class Method Summary collapse
- .matches_to_(s, expr) ⇒ Object
-
.option_value_(options, *keys, default_value) ⇒ Object
Resolves an option that may be named by one or more keys, preserving explicitly supplied +nil+/+false+ values (unlike
Hash#fetchwith||). -
.to_bool(s, **options) ⇒ Object
Attempts to parse the given string
sto a Boolean value, based on the givenoptions.
Class Method Details
.matches_to_(s, expr) ⇒ Object
58 59 60 61 62 63 64 65 66 |
# File 'lib/xqsr3/conversion/bool_parser.rb', line 58 def self.matches_to_ s, expr case expr when ::Regexp return expr =~ s else return s == expr end end |
.option_value_(options, *keys, default_value) ⇒ Object
Resolves an option that may be named by one or more keys, preserving
explicitly supplied +nil+/+false+ values (unlike Hash#fetch with ||).
70 71 72 73 74 75 76 77 78 |
# File 'lib/xqsr3/conversion/bool_parser.rb', line 70 def self.option_value_ , *keys, default_value keys.each do |key| return [key] if .key?(key) end default_value end |
.to_bool(s, **options) ⇒ Object
Attempts to parse the given string s to a Boolean value, based on the
given options
Signature
-
Parameters:
sThe string to be parsed;options(+Hash+) Options that control the behaviour of the method;
-
Options:
:false_values(+Array+) An array of strings or regular expressions against which to match for false value. Defaults toDEFAULT_FALSE_VALUES;:true_values(+Array+) An array of strings or regular expressions against which to match for true value. Defaults toDEFAULT_TRUE_VALUES;:default_valueAn object to be returned if matching fails. Defaults tonil. Alias::default;:false_valueAn object to be returned if matching succeeds to match against:false_values. Defaults tofalse. Alias::false;:true_valueAn object to be returned if matching succeeds to match against:true_values. Defaults totrue. Alias::true;
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
# File 'lib/xqsr3/conversion/bool_parser.rb', line 102 def self.to_bool s, ** true_values = [:true_values] || DEFAULT_TRUE_VALUES true_values = [ true_values ] unless true_values.is_a? ::Array false_values = [:false_values] || DEFAULT_FALSE_VALUES false_values = [ false_values ] unless false_values.is_a? ::Array default_value = self.option_value_ , :default_value, :default, nil true_value = self.option_value_ , :true_value, :true, true false_value = self.option_value_ , :false_value, :false, false return true_value if true_values.any? { |v| self.matches_to_ s, v } return false_value if false_values.any? { |v| self.matches_to_ s, v } return default_value end |