Sha256: 2ef78adb66f115e3bd07c38008f755e24a8c526a7d666b2f0c9465c0627d1de1

Contents?: true

Size: 1.1 KB

Versions: 1

Compression:

Stored size: 1.1 KB

Contents

# typed: strict

module Mocktail
  class CreatesIdentifier
    extend T::Sig

    KEYWORDS = T.let(%w[__FILE__ __LINE__ alias and begin BEGIN break case class def defined? do else elsif end END ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield], T::Array[String])

    sig { params(s: T.anything, default: String, max_length: Integer).returns(String) }
    def create(s, default: "identifier", max_length: 24)
      case s
      when Kernel
        id = (s.to_s.downcase
          .gsub(/:0x[0-9a-f]+/, "") # Lazy attempt to wipe any Object:0x802beef identifiers
          .gsub(/[^\w\s]/, "")
          .gsub(/^\d+/, "")[0...max_length] || "")
          .strip
          .gsub(/\s+/, "_") # snake_case

        if id.empty?
          default
        else
          unreserved(id, default)
        end
      else
        default
      end
    end

    private

    sig { params(id: String, default: String).returns(String) }
    def unreserved(id, default)
      return id unless KEYWORDS.include?(id)

      "#{id}_#{default}"
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mocktail-2.0.0 lib/mocktail/sorbet/mocktail/share/creates_identifier.rb