36進数のランダム乱数


サイト(ドメイン)名や、ユーザ名、パスワードなどを考えるのに適当な言葉を考えるのがたいへんなので、4桁の36進法、36進数の乱数を発生させて考える種にしています。Rubyで作っているので、これをerbで書いてサイトに載せたいと思い、作ってみました。

http://www.bp7e.com/rand36/rand36.rhtml

作り方:
1.htaccessを編集
2.cgi-bin/erb.cgiの編集
3.rand36.rhtml

少しコツがあるので備忘を書いておきます。以下の設定で、さくらインターネットでもドリームホストでも動いているのでたぶん間違いないと思います。

まずdot+htaccessはこんな感じ。

Options +ExecCGI
AddType text/html .cgi .pl .rb
AddHandler cgi-script .cgi .pl .rb
AddType application/x-httpd-eruby .rhtml
Action  application/x-httpd-eruby /cgi-bin/erb.cgi
DirectoryIndex index.html index.shtml index.rhtml

cgi-bin/erb.cgiはサイトにあったそのまま。

#!/usr/bin/ruby

# erb.cgi
#
# Apache script handler for .rhtml files
# based on work by Brian Bugh and Paul McArdle
# see http://dekstop.de/weblog/2006/01/rhtml_on_osx_with_apache_and_erb/
#
# Martin Dittus (martin@dekstop.de), 2006-01-09
# last change: 2006-01-11

require 'time'
require 'erb'

time = Time.now.httpdate

HEADERS = <<EOF
Date: #{ time }
Server: #{ ENV['SERVER_SOFTWARE'] }
Last-Modified: #{ time }
Content-Type: text/html

EOF

begin

  path = nil
  if (ENV['PATH_TRANSLATED'])
    path = ENV['PATH_TRANSLATED']
  else
    file_path = ENV['REDIRECT_URL'].include?(File.basename(__FILE__)) ? ENV['SCRIPT_URL'] : ENV['REDIRECT_URL']
    path = File.expand_path(ENV['DOCUMENT_ROOT'] + '/' + file_path)
    raise "Attempt to access invalid path: #{path}" unless path.index(ENV['DOCUMENT_ROOT']) == 0
  end
  erb = File.open(path) { |f| ERB.new(f.read) }
  print HEADERS + erb.result(binding)

rescue Exception

  print "Content-Type: text/html\n\n"

  # error message
  print "<h1>Script Error</h1>"
  print "<pre>#{ $! }</pre>"

  # debug info
  print "<h2>Backtrace</h2>"
  print "<pre>#{$!.backtrace.join("\n")}</pre>"

  print "<h2>Environment</h2>"
  print "<pre>#{ENV.keys.map { |key| key + ' = ' + ENV[key] + "\n"} }</pre>"

  print "<hr>"
  print "<i>#{__FILE__} -- #{time}</i>"

end


こうしておいて、rand36.rhtmlが以下のようになります。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>generate 36 radix numbers</title>
<%
require 'cgi'
@@cgi = CGI.new
def rand36(n)
ary = %w(0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)
strng = ""
i = n
for i in 1..n do
  strng = strng + ary[rand(36)]
end
return strng
end

if @@cgi.has_key?('digits')
  number = @@cgi['digits'].to_i
else
  number = 4
end

number = 4 if number < 1
%>
</head>
<body>
<h1><%= rand36(number) %></h1>
<p>
えっとこれは左上にあるのはランダムに発生した36進数です。ドメイン名やパスワードなど作るときのアイデア出しの用途に使います。下記に欲しい数の桁数を入れて送信して下さい。</p>
<form method="post" action="rand36.rhtml">
<input type="text" name="digits" size=5>
<input type="submit" value="送信">
</form>
</body>
</html>