Skip to content

Instantly share code, notes, and snippets.

@jopotts
Created January 30, 2014 11:14
Show Gist options
  • Select an option

  • Save jopotts/8706578 to your computer and use it in GitHub Desktop.

Select an option

Save jopotts/8706578 to your computer and use it in GitHub Desktop.

Revisions

  1. jopotts created this gist Jan 30, 2014.
    35 changes: 35 additions & 0 deletions random_string.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    module RandomString

    HUMAN = %w{2 3 4 6 7 9 a c d e f g h j k m n p q r t v w x y}
    LOWER = [*'a'..'z']
    PARAM = [*'a'..'z', *0..9]
    FULL = [*'a'..'z', *'A'..'Z', *0..9]
    MIXED = [*'a'..'z', *'A'..'Z']

    def self.by_rand(length = 8, set = :full)
    chars = get_chars(set)
    set_length = chars.length
    (0...length).map { chars[SecureRandom.random_number(set_length)] }.join
    end

    def self.by_sample(length = 8, set = :full)
    chars = get_chars(set)
    [].fill(0, length) { chars.sample }.join
    end

    def self.by_shuffle(length = 8, set = :full)
    get_chars(set).shuffle[0, length].join
    end

    def self.token(length = 28)
    by_rand(length, :param)
    end

    private

    def self.get_chars(set)
    return set if set.kind_of? Array
    const_get(set.to_s.upcase)
    end

    end