Module: HoneyFormat::HeaderColumnConverter

Defined in:
lib/honey_format/converters/header_column_converter.rb

Overview

Header column converter

Constant Summary collapse

BRACKETS =

Bracket character matcher

/\(|\[|\{|\)|\]|\}/.freeze
SEPS =

Separator characters

/'|"|\||\*|\^|\&|%|\$|€|£|#/.freeze
SPACES =

Space characters

/[[:space:]]+/.freeze
NON_PRINT =

Non-printable characters

/[^[:print:]]/.freeze
ZERO_WIDTH =

zero-width characters - see stackoverflow.com/q/50647999

/[\u200B-\u200D\uFEFF]/.freeze
REPLACE_MAP =

Replace map

[
  [/\\/, '/'],       # replace "\" with "/"
  [/ \(/, '('],      # replace " (" with "("
  [/ \[/, '['],      # replace " [" with "["
  [/ \{/, '{'],      # replace " {" with "{"
  [/ \{/, '{'],      # replace " {" with "{"
  [/\) /, ')'],      # replace ") " with ")"
  [/\] /, ']'],      # replace "] " with "]"
  [/\} /, '}'],      # replace "} " with "}"
  [/@/, '_at_'],     # replace "@' with "_at_"
  [BRACKETS, '_'],   # replace (, [, {, ), ] and } with "_"
  [SPACES, '_'],     # replace one or more space chars with "_"
  [/-/, '_'],        # replace "-" with "_"
  [/\.|,/, '_'],     # replace "." and "," with "_"
  [/::/, '_'],       # replace "::" with "_"
  [%r{/}, '_'],      # replace "/" with "_"
  [SEPS, '_'],       # replace separator chars with "_"
  [/_+/, '_'],       # replace one or more "_" with single "_"
  [NON_PRINT, ''],   # remove non-printable characters
  [ZERO_WIDTH, ''],  # remove zero-width characters
  [/\A_+/, ''],      # remove leading "_"
  [/_+\z/, ''],      # remove trailing "_"
].map { |e| e.map(&:freeze).freeze }.freeze

Class Method Summary collapse

Class Method Details

.call(column, index = nil) ⇒ Symbol

Returns converted value and mutates the argument.

Examples:

Convert simple header

HeaderColumnConverter.call("  User name ") #=> "user_name"

Convert complex header

HeaderColumnConverter.call(" First name (user)") #=> :'first_name(user)'

Parameters:

  • column (String, Symbol)

    the string to be cleaned.

  • index (Integer) (defaults to: nil)

    the column index.

Returns:

  • (Symbol)

    the cleaned header column.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/honey_format/converters/header_column_converter.rb', line 54

def self.call(column, index = nil)
  if column.nil? || column.empty?
    raise(ArgumentError, "column and column index can't be blank/nil") unless index

    return :"column#{index}"
  end

  column = column.to_s.dup
  column.strip!
  column.downcase!
  REPLACE_MAP.each do |data|
    from, to = data
    column.gsub!(from, to)
  end
  column.to_sym
end