summaryrefslogtreecommitdiff
path: root/lib/trocla/util.rb
blob: 78462f5cf805f75c4439a2ab1adcab04f7b4614a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
require 'securerandom'
class Trocla
  class Util
    class << self
      def random_str(length=12, charset='default')
        _charsets = charsets[charset]
        (1..length).collect{|a| _charsets[SecureRandom.random_number(_charsets.size)] }.join.to_s
      end

      def salt(length=8)
        (1..length).collect{|a| alphanumeric[SecureRandom.random_number(alphanumeric.size)] }.join.to_s
      end

      private

      def charsets
        @charsets ||= {
          'default'       => chars,
          'alphanumeric'  => alphanumeric,
          'shellsafe'     => shellsafe,
        }
      end

      def chars
        @chars ||= shellsafe + special_chars
      end
      def shellsafe
        @chars ||= alphanumeric + shellsafe_chars
      end
      def alphanumeric
        @alphanumeric ||= ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
      end
      def special_chars
        @special_chars ||= "*()&![]{}-".split(//)
      end
      def shellsafe_chars
        @shellsafe_chars ||= "+%/@=?_.,:".split(//)
      end
    end
  end
end