Class: EasyPin::Tumbler
- Inherits:
-
Object
- Object
- EasyPin::Tumbler
- Defined in:
- lib/easy_pin.rb
Instance Method Summary collapse
-
#initialize(dictionary, random, max_width = 32) ⇒ Tumbler
constructor
A new instance of Tumbler.
- #tumble(parts) ⇒ Object
- #untumble(parts) ⇒ Object
- #validate(parts) ⇒ Object
Constructor Details
#initialize(dictionary, random, max_width = 32) ⇒ Tumbler
Returns a new instance of Tumbler.
136 137 138 139 140 |
# File 'lib/easy_pin.rb', line 136 def initialize(dictionary, random, max_width = 32) raise InvalidConfig, 'Dictionary must have more than one item' if dictionary.size < 2 @shuffle = (0..max_width-1).map{ dictionary.shuffle(random: random) } @unshuffle = @shuffle.map{ |dict| Hash[dict.each_with_index.map{|a,b| [a,b]}] } end |
Instance Method Details
#tumble(parts) ⇒ Object
142 143 144 145 146 147 |
# File 'lib/easy_pin.rb', line 142 def tumble(parts) validate parts res = [] parts.each_with_index{|part, index| res << @shuffle.fetch(index).fetch(part)} res end |
#untumble(parts) ⇒ Object
149 150 151 152 153 154 |
# File 'lib/easy_pin.rb', line 149 def untumble(parts) validate parts res = [] parts.each_with_index{|part, index| res << @unshuffle.fetch(index).fetch(part)} res end |
#validate(parts) ⇒ Object
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
# File 'lib/easy_pin.rb', line 156 def validate(parts) raise InvalidInput, 'input has too many values' unless parts.length < @shuffle.length parts.each_with_index do |part, index| case part when Numeric max = @shuffle.fetch(index).length - 1 raise InvalidInput, "#{part} is not within #{0} and #{max}" unless part <= max && part >= 0 when String raise InvalidInput, "'#{part}' is not a valid value" unless @unshuffle.fetch(index).key?(part) else raise InvalidInput, "#{part.class} is not a valid input type" end end end |