Sha256: e99f4276eabe419cb779896a3b2e679561eb1c904f4d732ddbe121639fc3f826

Contents?: true

Size: 1.17 KB

Versions: 4

Compression:

Stored size: 1.17 KB

Contents

# frozen_string_literal: true

module Lutaml
  module Model
    module Utils
      class << self
        # Convert string to camel case
        def camel_case(str)
          return "" if str.nil? || str.empty?

          str.split("/").map { |part| camelize_part(part) }.join("::")
        end

        # Convert string to class name
        def classify(str)
          str = str.to_s.delete(".")
          str = str.sub(/^[a-z\d]*/) { |match| camel_case(match) || match }

          str.gsub("::", "/").gsub(%r{(?:_|-|(/))([a-z\d]*)}i) do
            word = Regexp.last_match(2)
            substituted = camel_case(word) || word
            Regexp.last_match(1) ? "::#{substituted}" : substituted
          end
        end

        # Convert string to snake case
        def snake_case(str)
          str = str.to_s.tr(".", "_")
          return str unless /[A-Z-]|::/.match?(str)

          str.gsub("::", "/")
            .gsub(/([A-Z]+)(?=[A-Z][a-z])|([a-z\d])(?=[A-Z])/) { "#{$1 || $2}_" }
            .tr("-", "_")
            .downcase
        end

        private

        def camelize_part(part)
          part.gsub(/(?:_|-|^)([a-z\d])/i) { $1.upcase }
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
lutaml-model-0.3.10 lib/lutaml/model/utils.rb
lutaml-model-0.3.9 lib/lutaml/model/utils.rb
lutaml-model-0.3.8 lib/lutaml/model/utils.rb
lutaml-model-0.3.7 lib/lutaml/model/utils.rb