Class: Localize::Formats

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

Class Method Summary collapse

Class Method Details

.date(source, format = :full) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/localize/formats.rb', line 37

def date(source, format = :full)
  locale = Localize.trans[:formats]['date']
  format = locale['format'][format]

  format.gsub!(/%a/, locale['day_names']['short'][source.wday])
  format.gsub!(/%A/, locale['day_names']['full'][source.wday])
  format.gsub!(/%b/, locale['mon_names']['short'][source.mon-1])
  format.gsub!(/%B/, locale['mon_names']['full'][source.mon-1])

  source.strftime(format)
end

.number(num) ⇒ Object

Based on snippet on rubygarden



50
51
52
53
54
55
56
57
# File 'lib/localize/formats.rb', line 50

def number(num)
  locale = Localize.trans[:formats]['number']
  separator = locale['separator'] || ''
  decimal_point = locale['dec_point'] || '.'
  num_parts = num.to_s.split('.')
  x = num_parts[0].reverse.scan(/.{1,3}/).join(separator).reverse
  x << decimal_point + num_parts[1]
end

.phone(str, format = :full) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/localize/formats.rb', line 6

def phone(str, format = :full)
  require 'strscan'
  pattern = Localize.trans[:formats]['phone'][format]
  slots = pattern.count('#')
  source = str.to_s

  if source.length < slots
    keepCount = source.length
    leftmost, rightmost = 0, pattern.length - 1

    leftmost = (1...keepCount).inject(pattern.rindex('#')) {
        |leftmost, n| pattern.rindex('#', leftmost - 1) }

    pattern = pattern[leftmost..rightmost]
  end

  scanner = ::StringScanner.new(pattern)
  sourceIndex = 0
  result = ''
  fixRegexp = Regexp.new(Regexp.escape('#'))
  while not scanner.eos?
    if scanner.scan(fixRegexp) then
      result += source[sourceIndex].chr
      sourceIndex += 1
    else
      result += scanner.getch
    end
  end
  result
end