module CurrencyToWords

Public Instance Methods

currency_to_words(number, options = {}) click to toggle source
# File lib/currency_to_words.rb, line 8
def currency_to_words number, options = {}
  # scopes
  scope = [:number, :currency_in_words]
  options_precision_scope = [:number, :currency_in_words, :options_precision]

  # format of number
  format = (I18n.t :format, scope: scope)

  # options for precision to split int and decimal part
  options_precision = {
    :precision => (I18n.t :precision, scope: options_precision_scope),
    :delimiter => (I18n.t :delimiter, scope: options_precision_scope),
    :significant => (I18n.t :significant, scope: options_precision_scope),
    :strip_insignificant_zeros => (I18n.t :strip_insignificant_zeros, scope: options_precision_scope),
    :separator => (I18n.t :separator, scope: options_precision_scope),
    :raise => (I18n.t :raise, scope: options_precision_scope)
  }

  # try to split number
  begin
    rounded_number = number_with_precision(number, options_precision)
  rescue ActionView::Helpers::NumberHelper::InvalidNumberError => e
    if options[:raise]
      raise
    else
      rounded_number = format.gsub(/%n/, e.number)
      return e.number.to_s.html_safe? ? rounded_number.html_safe : rounded_number
    end
  end

  # try to find locale class with language algorithm
  begin
    klass = "CurrencyToWords::#{I18n.locale.to_s.capitalize}Currency".constantize
  rescue NameError
    if options[:raise]
      raise NameError, "Implement a class #{options[:locale].to_s.capitalize}Currency to support this locale, please."
    else
      klass = CsCurrency
    end
  end

  # map number parts
  number_parts = rounded_number.split(options_precision[:separator]).map(&:to_i)

  # Create instance of base class and try to process through.
  base_class = CurrencyToWords::Currency.new(klass.new, number_parts, options)
  processed_number = base_class.process

  # return formatted number
  format.gsub(/%n/, processed_number).html_safe
end