Method: Rsmart::ETL.parse_string

Defined in:
lib/rsmart_toolbox/etl.rb

.parse_string(str, opt = { strict: true, required: false, escape_single_quotes: true }) ⇒ String

Parses a string using common parsing behavior with options. This method forms the foundation of all the other parsing methods.

Examples:

nil or empty inputs will return the empty String by default

'' == parse_string(nil) && '' == parse_string('')

Parameters:

  • str (String)

    the String to be parsed.

  • opt (Hash) (defaults to: { strict: true, required: false, escape_single_quotes: true })

    a customizable set of options

Options Hash (opt):

  • :default (String, #to_s)

    the default return value if str is empty. Must respond to #to_s

  • :escape_single_quotes (Boolean)

    escape single quote characters.

  • :length (Integer)

    raise a TextParseError if str.length > :length.

  • :name (String)

    the name of the field being parsed. Used only for error handling.

  • :required (Boolean)

    raise a TextParseError if str is empty.

  • :strict (Boolean)

    strict length checking will produce errors instead of warnings.

  • :valid_values (Array<Object>, Regexp)

    all of the possible valid values.

Returns:

  • (String)

    the parsed results. nil or empty inputs will return the empty String by default(i.e. ”).

Raises:

See Also:



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/rsmart_toolbox/etl.rb', line 173

def self.parse_string(str, opt={ strict: true, required: false, escape_single_quotes: true })
  opt[:strict] = true if opt[:strict].nil?
  opt[:escape_single_quotes] = true if opt[:escape_single_quotes].nil?
  retval = encode str.to_s.strip
  if opt[:required] && retval.empty?
    raise Rsmart::ETL::error TextParseError.new "Required data element '#{opt[:name]}' not found: '#{str}'"
  end
  if opt[:default] && retval.empty?
    retval = opt[:default].to_s
  end
  if opt[:length] && retval.length > opt[:length].to_i
    detail = "#{opt[:name]}.length > #{opt[:length]}: '#{str}'-->'#{str[0..(opt[:length] - 1)]}'"
    if opt[:strict]
      raise Rsmart::ETL::error TextParseError.new "Data exceeds maximum field length: #{detail}"
    end
    Rsmart::ETL::warning "Data will be truncated: #{detail}"
  end
  if opt[:valid_values] && ! valid_value(retval, opt[:valid_values], opt)
    raise Rsmart::ETL::error TextParseError.new "Illegal #{opt[:name]}: value '#{str}' not found in: #{opt[:valid_values]}"
  end
  if opt[:escape_single_quotes]
    retval = escape_single_quotes retval
  end
  return retval
end