Class: Timeliness::Format

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/timeliness/format.rb

Constant Summary collapse

CompilationFailed =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#abbr_month_names, #full_hour, #i18n_loaded?, #microseconds, #month_index, #month_names, #offset_in_seconds, #unambiguous_year

Constructor Details

#initialize(format_string) ⇒ Format

Returns a new instance of Format.



9
10
11
# File 'lib/timeliness/format.rb', line 9

def initialize(format_string)
  @format_string = format_string
end

Instance Attribute Details

#format_stringObject (readonly)

Returns the value of attribute format_string.



7
8
9
# File 'lib/timeliness/format.rb', line 7

def format_string
  @format_string
end

#regexpObject (readonly)

Returns the value of attribute regexp.



7
8
9
# File 'lib/timeliness/format.rb', line 7

def regexp
  @regexp
end

#regexp_stringObject (readonly)

Returns the value of attribute regexp_string.



7
8
9
# File 'lib/timeliness/format.rb', line 7

def regexp_string
  @regexp_string
end

#token_countObject (readonly)

Returns the value of attribute token_count.



7
8
9
# File 'lib/timeliness/format.rb', line 7

def token_count
  @token_count
end

Instance Method Details

#compile!Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/timeliness/format.rb', line 13

def compile!
  @token_count = 0
  found_tokens, token_order = [], []

  format = format_string.dup
  format.gsub!(/([\.\\])/, '\\\\\1') # escapes dots and backslashes

  # Substitute tokens with numbered placeholder
  Definitions.sorted_token_keys.each do |token|
    count = 0
    format.gsub!(token) do
      token_regexp_str, arg_key = Definitions.format_tokens[token]
      token_index = found_tokens.size

      if arg_key
        raise CompilationFailed, "Token '#{token}' was found more than once in format '#{format_string}'. This has unexpected effects should be removed." if count > 0
        count += 1

        token_regexp_str = "(#{token_regexp_str})"
        @token_count += 1
      end
      found_tokens << [ token_regexp_str, arg_key ]

      "%<#{token_index}>"
    end
  end

  # Replace placeholders with token regexps
  format.gsub!(/%<(\d+)>/) do
    token_regexp_str, arg_key = found_tokens[$1.to_i]
    token_order << arg_key
    token_regexp_str
  end

  define_process_method(token_order.compact)
  @regexp_string = format
  @regexp = Regexp.new("^(?>#{format})$")
  self
rescue => ex
  raise CompilationFailed, "The format '#{format_string}' failed to compile using regexp string #{format}. Error message: #{ex.inspect}"
end

#process(*args) ⇒ Object

Redefined on compile



56
# File 'lib/timeliness/format.rb', line 56

def process(*args); end