Class: CreateRailsMysqlDb::Application

Inherits:
Object
  • Object
show all
Defined in:
lib/create_rails_mysql_db.rb

Class Method Summary collapse

Class Method Details

.run!(*arguments) ⇒ Object



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
# File 'lib/create_rails_mysql_db.rb', line 4

def run!(*arguments)

  require 'rubygems'
  require 'yaml'

  @DBPATH='config/database.yml'
  @DBTYPES=['mysql', 'mysql2']

  if arguments.include?('-h')
    puts  "create_rails_mysql_db\nWithout options reads config/database.yml and create listed databases, grant access to username\n-g : options to generate new password, and replace username to database name\n          eos\n    exit\n  end\n\n  generate_password=arguments.include?('-g')\n  puts \"Warning if password empty username=database name, new password will be generated\\nconfig/database.yml will be overwrited\\n\" if (generate_password)\n\n  begin\n\n    def newpwd(len)\n      chars = (\"a\"..\"z\").to_a + (\"A\"..\"Z\").to_a + (\"0\"..\"9\").to_a\n      newpass = \"\"\n      1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }\n      return newpass\n    end\n    newpass = newpwd(8)\n    changed=0\n\n    File.open(@DBPATH) do |f|\n      dbconf=YAML.load(f)\n      dbconf.each do |type,db| \n        raise 'Adapter must be mysql' unless @DBTYPES.include?(db['adapter']) \n        raise 'Not defined username' unless db['username']\n        if !db['password'] && generate_password\n          dbconf[type]['password'] = newpass\n          dbconf[type]['username'] = dbconf[type]['database'].length>16 ? dbconf[type]['database'].gsub(/(\\_.{4}).*/, '\\1') : dbconf[type]['database']\n          raise 'Too long username' if dbconf[type]['username'].length>16\n          changed+=1\n        elsif !db['password']\n          raise 'Not defined password' unless db['password']\n        end\n        raise 'Too long username' if dbconf[type]['username'].length>16\n      end\n\n      File.open(@DBPATH, \"w\") { |f| YAML::dump(dbconf, f) } if (changed>0)\n      puts \"Enter mysql root password:\"\n      STDOUT.flush\n      system \"stty -echo\" \n      mysql_root=STDIN.gets.gsub(\"\\n\", \"\")\n      system \"stty echo\" \n      dbconf.each do |type,db|\n        mysql_command=\"mysql -uroot -p\\\"\#{mysql_root}\\\" -e \\\"create database \#{db['database']}; grant all on \#{db['database']}.* to \#{db['username']}@'localhost' identified by '\#{db['password']}'\\\";\"\n        system(mysql_command)\n      end\n    end\n  rescue Errno::ENOENT => e\n    puts \"Can't open \#{@DBPATH}\"\n  rescue ArgumentError, SyntaxError => e\n    puts \"Error in yaml format\"\n  rescue => e\n    puts e.message\n  end\n  return 0\nend\n"