Sha256: c3efd3dffef8590228c7d09460662314d04f414129a7fd1373ac49167d0771f2

Contents?: true

Size: 801 Bytes

Versions: 2

Compression:

Stored size: 801 Bytes

Contents

# frozen_string_literal: true

module FastUnderscore
  # Uses ActiveSupport's `acronym_regex` method to construct a memoized pattern
  # for replacing acronyms within strings that need to be underscored.
  module AcronymRegex
    def self.pattern
      return @pattern if defined?(@pattern)

      acronym_regex = ActiveSupport::Inflector.inflections.acronym_regex
      @pattern ||= /(?:(?<=([A-Za-z\d]))|\b)(#{acronym_regex})(?=\b|[^a-z])/
    end

    def underscore(string)
      return string unless /[A-Z-]|::/.match?(string)

      response = string.dup
      response.gsub!(AcronymRegex.pattern) { "#{$1 && '_'}#{$2.downcase}" }

      FastUnderscore.underscore(response)
    end
  end

  class << ActiveSupport::Inflector
    alias as_underscore underscore
    include AcronymRegex
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
fast_underscore-0.3.1 lib/fast_underscore/acronym_regex.rb
fast_underscore-0.3.0 lib/fast_underscore/acronym_regex.rb