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.



11
12
13
# File 'lib/timeliness/format.rb', line 11

def initialize(format_string)
  @format_string = format_string
end

Instance Attribute Details

#format_stringObject (readonly)

Returns the value of attribute format_string.



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

def format_string
  @format_string
end

#regexpObject (readonly)

Returns the value of attribute regexp.



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

def regexp
  @regexp
end

#regexp_stringObject (readonly)

Returns the value of attribute regexp_string.



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

def regexp_string
  @regexp_string
end

#token_countObject (readonly)

Returns the value of attribute token_count.



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

def token_count
  @token_count
end

Instance Method Details

#compile!Object



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
54
55
56
57
# File 'lib/timeliness/format.rb', line 15

def compile!
  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|
    format.gsub!(token) do
      token_regexp_str, arg_key = Definitions.format_tokens[token]

      if arg_key && found_tokens.rassoc(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
      end

      found_tokens << [ token_regexp_str, arg_key ]

      token_index = found_tokens.size - 1
      "%<#{token_index}>"
    end
  end

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

    if arg_key
      token_order << arg_key
      "(#{token_regexp_str})"
    else
      token_regexp_str
    end
  end

  @token_count = token_order.size

  define_process_method(token_order)
  @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



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

def process(*args); end