Sha256: 43ee43ebf0c37a099dfb55a51e634b3ddef13943e391993388965372c16d6e0f

Contents?: true

Size: 1.87 KB

Versions: 8

Compression:

Stored size: 1.87 KB

Contents

module Xi::CoreExt
  # String Inflectors, taken from ActiveSupport 5.0 source code
  module String
    # Converts strings to UpperCamelCase.
    # If the +uppercase_first_letter+ parameter is set to false, then produces
    # lowerCamelCase.
    #
    # Also converts '/' to '::' which is useful for converting
    # paths to namespaces.
    #
    #   camelize('active_model')                # => "ActiveModel"
    #   camelize('active_model', false)         # => "activeModel"
    #   camelize('active_model/errors')         # => "ActiveModel::Errors"
    #   camelize('active_model/errors', false)  # => "activeModel::Errors"
    #
    # As a rule of thumb you can think of +camelize+ as the inverse of
    # #underscore, though there are cases where that does not hold:
    #
    #   camelize(underscore('SSLError'))        # => "SslError"
    def camelize
      string = self.sub(/^[a-z\d]*/) { |match| match.capitalize }
      string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{$2.capitalize}" }
      string.gsub!('/'.freeze, '::'.freeze)
      string
    end

    # Makes an underscored, lowercase form from the expression in the string.
    #
    # Changes '::' to '/' to convert namespaces to paths.
    #
    #   underscore('ActiveModel')         # => "active_model"
    #   underscore('ActiveModel::Errors') # => "active_model/errors"
    #
    # As a rule of thumb you can think of +underscore+ as the inverse of
    # #camelize, though there are cases where that does not hold:
    #
    #   camelize(underscore('SSLError'))  # => "SslError"
    def underscore
      return self unless self =~ /[A-Z-]|::/
      word = self.to_s.gsub('::'.freeze, '/'.freeze)
      word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2'.freeze)
      word.gsub!(/([a-z\d])([A-Z])/, '\1_\2'.freeze)
      word.tr!("-".freeze, "_".freeze)
      word.downcase!
      word
    end
  end
end

class String
  include Xi::CoreExt::String
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
xi-lang-0.2.5 lib/xi/core_ext/string.rb
xi-lang-0.2.4 lib/xi/core_ext/string.rb
xi-lang-0.2.3 lib/xi/core_ext/string.rb
xi-lang-0.2.2 lib/xi/core_ext/string.rb
xi-lang-0.2.1 lib/xi/core_ext/string.rb
xi-lang-0.2.0 lib/xi/core_ext/string.rb
xi-lang-0.1.6 lib/xi/core_ext/string.rb
xi-lang-0.1.5 lib/xi/core_ext/string.rb