class Mascherari::Formatter

Attributes

format[R]
format_list[R]
value[R]
wildcard[R]

Public Class Methods

new(options = {}) click to toggle source
# File lib/mascherari/formatter.rb, line 3
def initialize(options = {})
  @format_list = Array(options.fetch :format)
  @wildcard = options.fetch :wildcard, "#"
end

Public Instance Methods

mask(raw_value) click to toggle source
# File lib/mascherari/formatter.rb, line 8
def mask(raw_value)
  prepare_value raw_value

  formatted? ? value : add_mask
end
unmask(raw_value) click to toggle source
# File lib/mascherari/formatter.rb, line 14
def unmask(raw_value)
  prepare_value raw_value

  formatted? ? remove_mask : value
end

Protected Instance Methods

add_mask() click to toggle source
# File lib/mascherari/formatter.rb, line 32
def add_mask
  format_sub(wildcard) { |_, index| value[index] }
end
find_format() click to toggle source
# File lib/mascherari/formatter.rb, line 64
def find_format
  format_for { formatted? } || format_for { wildcard_size? }
end
format_for() { || ... } click to toggle source
# File lib/mascherari/formatter.rb, line 68
def format_for(&block)
  format_list.any? { |format| @format = format; yield }
end
format_matcher(char) click to toggle source
# File lib/mascherari/formatter.rb, line 48
def format_matcher(char)
  wildcard?(char) ? '\S' : "\\#{char}"
end
format_regexp() click to toggle source
# File lib/mascherari/formatter.rb, line 44
def format_regexp
  /\A#{format_sub { |char| format_matcher char }}\z/
end
format_sub(pattern = /./) { |char, index| ... } click to toggle source
# File lib/mascherari/formatter.rb, line 40
def format_sub(pattern = /./, &block)
  format.gsub(pattern).each_with_index { |char, index| yield char, index }
end
formatted?() click to toggle source
# File lib/mascherari/formatter.rb, line 52
def formatted?
  value =~ format_regexp
end
prepare_value(raw_value) click to toggle source
# File lib/mascherari/formatter.rb, line 24
def prepare_value(raw_value)
  @value = raw_value.to_s

  unless find_format
    raise ArgumentError, "Value size don't match format"
  end
end
remove_mask() click to toggle source
# File lib/mascherari/formatter.rb, line 36
def remove_mask
  format_sub { |char, index| value[index] if wildcard?(char) }
end
wildcard?(char) click to toggle source
# File lib/mascherari/formatter.rb, line 60
def wildcard?(char)
  char == wildcard
end
wildcard_size?() click to toggle source
# File lib/mascherari/formatter.rb, line 56
def wildcard_size?
  value.size == format.scan(wildcard).size
end