Class: IceCube::StringBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/ice_cube/builders/string_builder.rb

Constant Summary collapse

NUMBER_SUFFIX =
['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']
SPECIAL_SUFFIX =
{ 11 => 'th', 12 => 'th', 13 => 'th', 14 => 'th' }

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeStringBuilder

Returns a new instance of StringBuilder.



7
8
9
# File 'lib/ice_cube/builders/string_builder.rb', line 7

def initialize
  @types = {}
end

Instance Attribute Details

#base=(value) ⇒ Object (writeonly)

Sets the attribute base

Parameters:

  • value

    the value to set the attribute base to.



5
6
7
# File 'lib/ice_cube/builders/string_builder.rb', line 5

def base=(value)
  @base = value
end

Class Method Details

.formatter(type) ⇒ Object



30
31
32
# File 'lib/ice_cube/builders/string_builder.rb', line 30

def formatter(type)
  @formatters[type]
end

.nice_number(number) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/ice_cube/builders/string_builder.rb', line 56

def nice_number(number)
  if number == -1
    'last'
  elsif number < -1
    suffix = SPECIAL_SUFFIX.include?(number) ?
      SPECIAL_SUFFIX[number] : NUMBER_SUFFIX[number.abs % 10]
    number.abs.to_s << suffix << ' to last'
  else
    suffix = SPECIAL_SUFFIX.include?(number) ?
      SPECIAL_SUFFIX[number] : NUMBER_SUFFIX[number.abs % 10]
    number.to_s << suffix  
  end
end

.register_formatter(type, &formatter) ⇒ Object



34
35
36
37
# File 'lib/ice_cube/builders/string_builder.rb', line 34

def register_formatter(type, &formatter)
  @formatters ||= {}
  @formatters[type] = formatter
end

.sentence(array) ⇒ Object

influenced by ActiveSupport’s to_sentence



47
48
49
50
51
52
53
54
# File 'lib/ice_cube/builders/string_builder.rb', line 47

def sentence(array)
  case array.length
  when 0 ; ''
  when 1 ; array[0].to_s
  when 2 ; "#{array[0]} and #{array[1]}"
  else ; "#{array[0...-1].join(', ')}, and #{array[-1]}"
  end
end

Instance Method Details

#piece(type, prefix = nil, suffix = nil) ⇒ Object



11
12
13
# File 'lib/ice_cube/builders/string_builder.rb', line 11

def piece(type, prefix = nil, suffix = nil)
  @types[type] ||= []
end

#to_sObject



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/ice_cube/builders/string_builder.rb', line 15

def to_s
  str = @base || ''
  res = @types.map do |type, segments|
    if f = self.class.formatter(type)
      str << ' ' + f.call(segments)
    else
      next if segments.empty?
      str << ' ' + self.class.sentence(segments)
    end
  end
  str
end