public
Fork of foca/utility_scripts
Description: Some utility scripts (the stuff I keep in ~/bin)
Clone URL: git://github.com/sabman/utility_scripts.git
Search Repo:
utility_scripts / passgen
100755 70 lines (60 sloc) 2.104 kb
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env ruby
 
%w( rubygems optparse ).each &method(:require)
 
class PassGrid
  ALPHANUMERIC = ('A'..'Z').to_a + (0..9).to_a.map {|i| i.to_s }
  EXTENDED = ALPHANUMERIC + %w( + - = _ ! / < > @ # $ % ^ & * \ ; : . , )
 
  def initialize(width, height, extended_charset = false, label = nil)
    @rows = []
    @width, @height = width, height
    @label = label
    self.characters = extended_charset
    populate
  end
 
  def print
    print_label
    @rows.each {|row| puts row.join(@height == 1 ? "" : " ") }
  end
 
  private
    def print_label
      return if @label.nil?
      puts @label
      puts "=" * (2 * @width - 1)
    end
    def populate
      @height.times do
        @rows << []
        @width.times { @rows.last << characters.sort_by { rand }.last.gsub(/\s+/, "") }
      end
    end
    def characters=(charset)
      @charset = ALPHANUMERIC
      return if charset.nil? || charset.empty?
 
      @charset += case charset
        when String then charset.split("").uniq
        when Enumerable then charset
        else EXTENDED
      end
    end
    def characters
      @charset.map do |char|
        rand(2).zero? ? char.downcase : char.upcase
      end
    end
end
 
if $0 == __FILE__
  options = { :extended => false, :width => 10, :height => 10, :label => nil, :help => false }
 
  opts = OptionParser.new do |opts|
    opts.on("-e [CHARSET]", "--extended [CHARSET]", "Extended character set") {|c| options[:extended] = c || true }
    opts.on("-w WIDTH", "--width WIDTH", /\d+/, "Width of the grid (default 10)") {|w| options[:width] = w.to_i }
    opts.on("-h HEIGHT", "--height HEIGHT", /\d+/, "Height of the grid (default 10)") {|h| options[:height] = h.to_i }
    opts.on("-l LABEL", "--label LABEL", "Label for the grid") {|l| options[:label] = l }
    opts.on_tail("--help", "Show this usage statement") { raise }
  end
 
  begin
    opts.parse!(ARGV)
  rescue Exception => e
    puts opts
    exit
  end
 
  PassGrid.new(options[:width], options[:height], options[:extended], options[:label]).print
end