Class: Inquirer
- Inherits:
-
Object
- Object
- Inquirer
- Defined in:
- lib/esm/extension/inquirer.rb
Overview
A base class that allows for creating classes that can be asked questions. Very similar to ActiveSupport::StringInquirer and ArrayInquirer, except stricter See initializer
Instance Method Summary collapse
-
#initialize(*predicates, default: nil) ⇒ Inquirer
constructor
A new instance of Inquirer.
-
#set(*predicates, unset: true) ⇒ Self
Sets the provided predicates to true.
- #to_a ⇒ Object
- #to_h ⇒ Object
- #to_s ⇒ Object
-
#unset(*predicates) ⇒ Self
Sets the provided predicates to false.
Constructor Details
#initialize(*predicates, default: nil) ⇒ Inquirer
Returns a new instance of Inquirer.
27 28 29 30 31 32 33 34 35 36 |
# File 'lib/esm/extension/inquirer.rb', line 27 def initialize(*predicates, default: nil) @predicates = predicates.map(&:to_sym) define_predicates if default default = [default] unless default.is_a?(Array) set(*default) end end |
Instance Method Details
#set(*predicates, unset: true) ⇒ Self
Sets the provided predicates to true
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/esm/extension/inquirer.rb', line 50 def set(*predicates, unset: true) predicates = predicates.map(&:to_sym) if (invalid_predicates = predicates - @predicates) && invalid_predicates.size > 0 raise ArgumentError, "#{invalid_predicates} are not allowed as predicates for #{self.class.name}. Valid options: #{@predicates}" end # Unset case unset when true unset(*@predicates) when Array, Symbol unset = [unset] unless unset.is_a?(Array) unset(*unset) end # Set predicates.each do |predicate| instance_variable_set(:"@#{predicate}", true) end self end |
#to_a ⇒ Object
97 98 99 |
# File 'lib/esm/extension/inquirer.rb', line 97 def to_a to_h.select { |_predicate, enabled| enabled }.keys end |
#to_h ⇒ Object
91 92 93 94 95 |
# File 'lib/esm/extension/inquirer.rb', line 91 def to_h @predicates.index_with do |predicate| instance_variable_get(:"@#{predicate}") end end |
#to_s ⇒ Object
101 102 103 104 105 106 107 108 109 |
# File 'lib/esm/extension/inquirer.rb', line 101 def to_s enabled_predicates = to_a if enabled_predicates.size > 1 enabled_predicates.to_s else enabled_predicates.first.to_s end end |
#unset(*predicates) ⇒ Self
Sets the provided predicates to false
81 82 83 84 85 86 87 88 89 |
# File 'lib/esm/extension/inquirer.rb', line 81 def unset(*predicates) predicates.map(&:to_sym).each do |predicate| next if @predicates.exclude?(predicate) instance_variable_set(:"@#{predicate}", false) end self end |