Class: LocalPostal::Format

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Model
Defined in:
lib/local_postal/format.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_country_code(code) ⇒ LocalPostal::Format

Constructs an instance of LocalPostal::Format by looking up the supplied country code in config/formats/*.json.

Parameters:

  • code (String)

    The 2-character country code.

Returns:

Raises:

  • (ArgumentError)

    If the code is not exactly 2 characters.

  • (ArgumentError)

    If the supplied country code is not supported.



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/local_postal/format.rb', line 36

def self.from_country_code(code)
  code = "#{code}".upcase

  fail ArgumentError, "#{code} is an invalid code", caller if code.length != 2

  path = File.join(LocalPostal.root, 'config', 'formats', "#{code}.json")

  fail ArgumentError, "#{code} unsupported", caller unless File.file?(path)

  from_json(path)
end

.from_json(path) ⇒ LocalPostal::Format

Constructs an instance of LocalPostal::Format from the supplied JSON file.

Parameters:

  • path (String)

    The full pathname of the JSON file.

Returns:



22
23
24
25
26
27
# File 'lib/local_postal/format.rb', line 22

def self.from_json(path)
  raw_json = File.read(path)
  parsed_json = JSON.parse(raw_json)

  new(parsed_json)
end

Instance Method Details

#apply(values) ⇒ String

Applies the formatting to the supplied values.

Parameters:

  • values (Hash)

    The address’ field values.

Returns:

  • (String)

    The address properly formatted for its country.



52
53
54
55
56
57
58
59
60
61
# File 'lib/local_postal/format.rb', line 52

def apply(values)
  values = values.map do |key, value|
    key = key.upcase if uppercase_fields.include?(key)
    value = "#{value}".upcase if uppercase_fields.include?("#{key}")

    [key, value]
  end

  formatted_string % values.to_h
end

#formatted_stringString

Converts the format provided in the JSON files into a valid Ruby formatted String that can be parsed using the modulus operator and a Hash.

Returns:

  • (String)

    A formatted string.



67
68
69
70
71
# File 'lib/local_postal/format.rb', line 67

def formatted_string
  format.dup.tap do |str|
    variables.each {|v| str.gsub!("%#{v}", "%{#{v}}") }
  end
end

#variablesArray

All of the variables found in the format.

Returns:

  • (Array)

    Variable names as Strings.



76
77
78
# File 'lib/local_postal/format.rb', line 76

def variables
  format.scan(/(%\w+)/).flatten.map {|v| v[1..v.length] }
end