Module: Normatron::Filters::UnderscoreFilter

Extended by:
Helpers
Defined in:
lib/normatron/filters/underscore_filter.rb

Overview

Makes an underscored lowercase form from the expression in the string.

Changes ‘::’ to ‘/’ to convert namespaces to paths.

As a rule of thumb you can think of underscore as the inverse of camelize, though there are cases where that does not hold:

“SSLError”.underscore.camelize # => “SslError”

Examples:

Out of box

UnderscoreFilter.call("ActiveRecord::Errors") #=> "active_record/errors"

Using as ActiveRecord::Base normalizer

normalize :attribute_a, :with => :underscore
normalize :attribute_b, :with => [:custom_filter, :underscore]
normalize :attribute_c, :with => [[:underscore, :lower]]
normalize :attribute_d, :with => [{:underscore => :lower}]
normalize :attribute_e, :with => [:custom_filter, [:underscore, :lower]]
normalize :attribute_f, :with => [:custom_filter, {:underscore => :lower}]

See Also:

Class Method Summary collapse

Methods included from Helpers

acronym_regex, acronyms, evaluate_regexp, inflections, mb_send

Class Method Details

.call(input) ⇒ String

Performs input conversion according to filter requirements.

This method returns the object itself when the first argument is not a String.

Parameters:

  • input (String)

    The String to be filtered

Returns:

  • (String)

    A new underscored String



39
40
41
42
43
44
45
46
47
48
# File 'lib/normatron/filters/underscore_filter.rb', line 39

def self.call(input)
  return input unless input.kind_of?(String)

  string = input.gsub(/::/, '/')
  string.gsub!(/#{acronym_regex}/) { "_#{$&}_".downcase }
  string.gsub!(/\b_|_\b/, "")
  string.gsub!(/([^\/\b_])(?=[\p{Lu}])/u) { "#{$&}_" }
  string.tr!("-", "_")
  mb_send(:downcase, string)
end