Class: SubCipher::SubCipherObject

Inherits:
Object
  • Object
show all
Defined in:
lib/sub_cipher.rb

Overview

The sub cipher class.

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ SubCipherObject

The sub cipher contructor.

Raises:


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/sub_cipher.rb', line 47

def initialize(options)
  opts = check_opt(options)
  opts.each do |key, value|
    if (!SUPPORTED_OPTS.key?(key) && !SUPPORTED_OPTS.values.map {|v| v[:abbr]}.include?(key))
      raise SubCipherError.new(:unknown_option, key)
    end
    case key
    when :seed
      @map = value.chars.to_a.uniq.shuffle
    when :map
      @map = value.chars.to_a.uniq
    when :keep_case
      @keep_case = (value ? true : false)
    end
  end
  support_keep_case = true
  @map.each do |m|
    if !ALPHABETS.include?(m.downcase)
      support_keep_case = false
      break
    end
  end
  @keep_case = (support_keep_case && @keep_case ? true : false)
  if @keep_case
    @map = @map.map{ |m| m.downcase }.uniq
  end
  seed = @map.sort
  @mapping = {}
  seed.each_with_index do |s, index|
    @mapping[s] = @map[index]
  end
end

Instance Method Details

#decode(str) ⇒ String

Decode the given string.


94
95
96
# File 'lib/sub_cipher.rb', line 94

def decode(str)
  str.chars.map { |c| convert(c, true) }.join
end

#encode(str) ⇒ String

Encode the given string.


85
86
87
# File 'lib/sub_cipher.rb', line 85

def encode(str)
  str.chars.map { |c| convert(c) }.join
end

#mapString

Show the map string, for mapping display. For example, if the seed string is “abc” and map string is “cab”, then the mapping is “a” => “c”, “b” => “a”, “c” => “b”.


103
104
105
# File 'lib/sub_cipher.rb', line 103

def map
  @map.join
end

#seedString

Show the seed string, for mapping display. For example, if the seed string is “abc” and map string is “cab”, then the mapping is “a” => “c”, “b” => “a”, “c” => “b”.


112
113
114
# File 'lib/sub_cipher.rb', line 112

def seed
  @map.sort.join
end