class EasyPin::Tumbler

Public Class Methods

new(dictionary, random, max_width = 32) click to toggle source
# 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

Public Instance Methods

tumble(parts) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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