Sha256: 462c6283358dfd49a10e2f9b88a05f069b48579e51d89938be4dee1b41f3206c

Contents?: true

Size: 1.62 KB

Versions: 11

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

module ConvenientService
  module Utils
    module String
      ##
      # Converts strings to UpperCamelCase (`capitalize_first_letter` option is set to `true` by default).
      # Implementation is very basic just to serve the need of this library.
      # More comprehensive solution can be found in Rails, for example:
      # - https://github.com/rails/rails/blob/5aaaa1630ae9a71b3c3ecc4dc46074d678c08d67/activesupport/lib/active_support/core_ext/string/inflections.rb#L103
      # - https://github.com/rails/rails/blob/5aaaa1630ae9a71b3c3ecc4dc46074d678c08d67/activesupport/lib/active_support/inflector/methods.rb#L53
      #
      class Camelize < Support::Command
        ##
        # @!attribute [r] string
        #   @return [#to_s]
        #
        attr_reader :string

        ##
        # @!attribute [r] capitalize_first_letter
        #   @return [Boolean]
        #
        attr_reader :capitalize_first_letter

        ##
        # @param string [Symbol, String]
        # @return [void]
        #
        def initialize(string, capitalize_first_letter: true)
          @string = string.to_s
          @capitalize_first_letter = capitalize_first_letter
        end

        ##
        # @return [String]
        #
        def call
          camelized = string.split(/[:_?!\-\ ]/).map { |part| upcase_first_char(part) }.join

          camelized[0] = camelized[0].downcase unless capitalize_first_letter

          camelized
        end

        private

        def upcase_first_char(part)
          return part if part.empty?

          "#{part[0].upcase}#{part[1..]}"
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
convenient_service-0.9.0 lib/convenient_service/utils/string/camelize.rb
convenient_service-0.8.0 lib/convenient_service/utils/string/camelize.rb
convenient_service-0.7.0 lib/convenient_service/utils/string/camelize.rb
convenient_service-0.6.0 lib/convenient_service/utils/string/camelize.rb
convenient_service-0.5.0 lib/convenient_service/utils/string/camelize.rb
convenient_service-0.4.0 lib/convenient_service/utils/string/camelize.rb
convenient_service-0.3.1 lib/convenient_service/utils/string/camelize.rb
convenient_service-0.3.0 lib/convenient_service/utils/string/camelize.rb
convenient_service-0.2.1 lib/convenient_service/utils/string/camelize.rb
convenient_service-0.2.0 lib/convenient_service/utils/string/camelize.rb
convenient_service-0.1.0 lib/convenient_service/utils/string/camelize.rb