Class: LocalPostal::Format
- Inherits:
-
Object
- Object
- LocalPostal::Format
- Includes:
- ActiveModel::Model
- Defined in:
- lib/local_postal/format.rb
Class Method Summary collapse
-
.from_country_code(code) ⇒ LocalPostal::Format
Constructs an instance of LocalPostal::Format by looking up the supplied country code in config/formats/*.json.
-
.from_json(path) ⇒ LocalPostal::Format
Constructs an instance of LocalPostal::Format from the supplied JSON file.
Instance Method Summary collapse
-
#apply(values) ⇒ String
Applies the formatting to the supplied values.
-
#formatted_string ⇒ String
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.
-
#variables ⇒ Array
All of the variables found in the format.
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.
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.
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.
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_string ⇒ String
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.
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 |
#variables ⇒ Array
All of the variables found in the format.
76 77 78 |
# File 'lib/local_postal/format.rb', line 76 def variables format.scan(/(%\w+)/).flatten.map {|v| v[1..v.length] } end |