lib/mascherari/formatter.rb in mascherari-0.0.1 vs lib/mascherari/formatter.rb in mascherari-0.0.2
- old
+ new
@@ -1,11 +1,9 @@
module Mascherari
class Formatter
- attr_reader :format, :wildcard
-
def initialize(options = {})
- @format = options.fetch :format
+ @format_list = Array(options.fetch :format)
@wildcard = options.fetch :wildcard, "#"
end
def mask(raw_value)
prepare_value raw_value
@@ -19,46 +17,56 @@
formatted? ? remove_mask : value
end
protected
- attr_reader :value
+ attr_reader :value, :format, :format_list, :wildcard
def prepare_value(raw_value)
@value = raw_value.to_s
- valid_value?
+ unless find_format
+ raise ArgumentError, "Value size don't match format"
+ end
end
def add_mask
- value_chars = value.chars
-
- format_chars do |char|
- wildcard?(char) ? value_chars.shift : char
- end
+ format_sub(wildcard) { |_, index| value[index] }
end
def remove_mask
- format_chars do |char, index|
- value[index] if wildcard?(char)
- end
+ format_sub { |char, index| value[index] if wildcard?(char) }
end
- def format_chars(&block)
- format.chars.map.with_index { |char, index| yield char, index }.join
+ def format_sub(pattern = /./, &block)
+ format.gsub(pattern).each_with_index { |char, index| yield char, index }
end
+ def format_regexp
+ /\A#{format_sub { |char| format_matcher char }}\z/
+ end
+
+ def format_matcher(char)
+ wildcard?(char) ? '\S' : "\\#{char}"
+ end
+
def formatted?
- value.size == format.size
+ value =~ format_regexp
end
+ def wildcard_size?
+ value.size == format.scan(wildcard).size
+ end
+
def wildcard?(char)
char == wildcard
end
- def valid_value?
- unless formatted? || value.size == format.scan(wildcard).size
- raise ArgumentError, "Value size don't match format"
- end
+ def find_format
+ format_for { formatted? } || format_for { wildcard_size? }
+ end
+
+ def format_for(&block)
+ format_list.any? { |format| @format = format; yield }
end
end
end