Class: ICU::NumberFormatting::CurrencyFormatter

Inherits:
BaseFormatter show all
Defined in:
lib/ffi-icu/number_formatting.rb

Overview

NumberFormatter

Instance Method Summary collapse

Methods inherited from BaseFormatter

#set_attributes

Constructor Details

#initialize(locale, style = :default) ⇒ CurrencyFormatter

Returns a new instance of CurrencyFormatter.



104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/ffi-icu/number_formatting.rb', line 104

def initialize(locale, style = :default)
  if %w(iso plural).include?((style || '').to_s)
    if Lib.version.to_a.first >= 53
      style = "currency_#{style}".to_sym
    else
      fail "Your version of ICU (#{Lib.version.to_a.join('.')}) does not support #{style} currency formatting (supported only in version >= 53)"
    end
  elsif style && style.to_sym != :default
    fail "The ffi-icu ruby gem does not support :#{default} currency formatting (only :default, :iso, and :plural)"
  else
    style = :currency
  end
  @f = make_formatter(style, locale)
end

Instance Method Details

#format(number, currency) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/ffi-icu/number_formatting.rb', line 119

def format(number, currency)
  needed_length = 0
  out_ptr = UCharPointer.new(needed_length)

  retried = false

  begin
    Lib.check_error do |error|
      needed_length = Lib.unum_format_currency(@f, number, UCharPointer.from_string(currency, 4), out_ptr, needed_length, nil, error)
    end
    out_ptr.string
  rescue BufferOverflowError
    raise BufferOverflowError, "needed: #{needed_length}" if retried
    out_ptr = out_ptr.resized_to needed_length
    retried = true
    retry
  end
end