Method: Faker::Base.parse

Defined in:
lib/faker.rb

.parse(key) ⇒ Object

Load formatted strings from the locale, “parsing” them into method calls that can be used to generate a formatted translation: e.g., “#first_name #last_name”.



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/faker.rb', line 132

def parse(key)
  fetched = fetch(key)
  parts = fetched.scan(/(\(?)#\{([A-Za-z]+\.)?([^}]+)\}([^#]+)?/).map do |prefix, kls, meth, etc|
    # If the token had a class Prefix (e.g., Name.first_name)
    # grab the constant, otherwise use self
    cls = kls ? Faker.const_get(kls.chop) : self

    # If an optional leading parentheses is not present, prefix.should == "", otherwise prefix.should == "("
    # In either case the information will be retained for reconstruction of the string.
    text = prefix

    # If the class has the method, call it, otherwise fetch the translation
    # (e.g., faker.phone_number.area_code)
    text += if cls.respond_to?(meth)
              cls.send(meth)
            else
              # Do just enough snake casing to convert PhoneNumber to phone_number
              key_path = cls.to_s.split('::').last.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase
              fetch("#{key_path}.#{meth.downcase}")
            end

    # And tack on spaces, commas, etc. left over in the string
    text + etc.to_s
  end
  # If the fetched key couldn't be parsed, then fallback to numerify
  parts.any? ? parts.join : numerify(fetched)
end