Class: Uncsv::KeyNormalizer

Inherits:
Object
  • Object
show all
Defined in:
lib/uncsv/key_normalizer.rb

Overview

Normalizes strings into a consistant format

Constant Summary collapse

DEFAULTS =

The default values applied if an attribute's value is not specified when constructing a new KeyNormalizer object.

{
  downcase: true,
  separator: '_'
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ KeyNormalizer

Create a new KeyNormalizer object.

Options will be set to the defaults unless overridden by the opts parameter.

Parameters:

  • opts (Hash) (defaults to: {})

    A hash of configuration options. See the individual attributes for detailed descriptions.



35
36
37
# File 'lib/uncsv/key_normalizer.rb', line 35

def initialize(opts = {})
  DEFAULTS.merge(opts).each { |k, v| public_send("#{k}=", v) }
end

Instance Attribute Details

#downcaseBoolean

Sets keys to all lower-case if set to true

Default: true

Returns:

  • (Boolean)

    Whether the key will be lower-cased



26
27
28
# File 'lib/uncsv/key_normalizer.rb', line 26

def downcase
  @downcase
end

#separatorString

A string to replace all non-alphanumeric characters in the key

Default: '_'. Can be set to an empty string to remove non-alphanumeric characters without replacing them.

Returns:

  • (String)

    The separator string



19
20
21
# File 'lib/uncsv/key_normalizer.rb', line 19

def separator
  @separator
end

Instance Method Details

#normalize(key) ⇒ String?

Normalize a key

Replaces non-alphanumeric characters with separator, then deduplicates underscores and trims them from the ends of the key. Then the key is lower-cased if downcase is set.

Parameters:

  • key (String, nil)

    The key field to normalize

Returns:

  • (String, nil)

    The normalized header field or nil if the input key is nil.



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/uncsv/key_normalizer.rb', line 48

def normalize(key)
  return nil if key.nil?

  key = key.gsub(/[^a-z0-9]+/i, separator)
  unless separator.empty?
    escaped_separator = Regexp.escape(separator)
    key.gsub!(/#{escaped_separator}{2,}/, separator)
    key.gsub!(/^#{escaped_separator}|#{escaped_separator}$/, '')
  end
  key.downcase! if downcase
  key
end