Class: Addressing::DefaultFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/addressing/default_formatter.rb

Direct Known Subclasses

PostalLabelFormatter

Constant Summary collapse

DEFAULT_OPTIONS =
{
  locale: "en",
  html: true,
  html_tag: "p",
  html_attributes: {translate: "no"}
}

Instance Method Summary collapse

Constructor Details

#initialize(default_options = {}) ⇒ DefaultFormatter

Returns a new instance of DefaultFormatter.



12
13
14
15
16
# File 'lib/addressing/default_formatter.rb', line 12

def initialize(default_options = {})
  assert_options(default_options)

  @default_options = self.class::DEFAULT_OPTIONS.merge(default_options)
end

Instance Method Details

#format(address, options = {}) ⇒ Object



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
# File 'lib/addressing/default_formatter.rb', line 18

def format(address, options = {})
  assert_options(options)

  options = @default_options.merge(options)
  address_format = AddressFormat.get(address.country_code)

  # Add the country to the bottom or the top of the format string,
  # depending on whether the format is minor-to-major or major-to-minor.
  format_string = if Locale.match_candidates(address_format.locale, address.locale)
    "%country\n" + address_format.local_format
  else
    address_format.format + "\n%country"
  end

  view = build_view(address, address_format, options)
  view = render_view(view)

  replacements = view.map { |key, element| ["%#{key}", element] }.to_h
  output = format_string.gsub(/%[a-z1-9_]+/) { |m| replacements[m] }
  output = clean_output(output)

  if options[:html]
    output = output.gsub("\n", "<br>\n")
    # Add the HTML wrapper element.
    output = render_html_element(value: "\n#{output}\n", html_tag: options[:html_tag], html_attributes: options[:html_attributes])
  end

  output
end