Sha256: 9fbc43c8fe28ac2e381bdfc045f12e9ec1953e612fe267902b09f3e8c63a03fa

Contents?: true

Size: 1.3 KB

Versions: 1

Compression:

Stored size: 1.3 KB

Contents

require 'all_your_base/are/belong_to_us'

class String
  class << self
    # Build a url/human-friendly random string. Defaults to 25 characters long.
    def friendly(length = 25)
      @friendly_characters ||= ['0'..'9', 'a'..'z', 'A'..'Z'].map(&:to_a).flatten!
      (1..length).map{@friendly_characters.sample}.join
    end

    # Build a completely unfriendly random string. Defaults to 25 characters long.
    def crazy(length = 25)
      @crazy_characters ||= ['0'..'9', 'a'..'z', 'A'..'Z'].map(&:to_a).flatten! + ["\\"] +
        ['(', ')', ' '] + %w(~ ` ! @ # $ % ^ & * _ - + = [ ] { } | ; : ' " , < . > / ?)
      (1..length).map{@crazy_characters.sample}.join
    end
  end

  # Translate a human-readable representation of an ObjectID instance back to an ObjectID.
  # Requires the all-your-base gem.
  def to_oid
    string = from_base_62.to_s(16)

    # replace leading zeroes that were lost during the hex conversion
    until string.length == 24
      string = '0' + string
    end

    BSON::ObjectID.from_string(string.reverse)
  end

  # For when you want to check for a string in a case-insensitive fashion. Mostly used in Mongo queries.
  def to_regex
    /^#{Regexp.escape(self)}$/i
  end

  # Convenience method, for whenever you need to pepper something.
  def peppered
    self + ENV['PEPPER']
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
junk_drawer-0.0.1 lib/core_extensions/string.rb