Class: DatabaseYML

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

Constant Summary collapse

SCRIPT_RAILS =
File.join('script', 'rails')
DRIVERS =
%W(mysql postgresql sqlite3)
TEMPLATES_DIR =
File.join(File.expand_path(File.dirname(__FILE__)), "templates")

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(database) ⇒ DatabaseYML

Returns a new instance of DatabaseYML.



14
15
16
# File 'lib/database_yml.rb', line 14

def initialize(database)
  @database = database || 'sqlite3'
end

Class Method Details

.in_rails_application? ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/database_yml.rb', line 39

def self.in_rails_application?
  File.exists?(SCRIPT_RAILS)
end

.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd)) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/database_yml.rb', line 43

def self.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd))
  File.exists?(File.join(path, SCRIPT_RAILS)) || !path.root? && in_rails_application_subdirectory?(path.parent)
end

Instance Method Details

#create! ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/database_yml.rb', line 18

def create!

  return unless DRIVERS.include? @database

  cwd = Dir.pwd
  return unless self.class.in_rails_application? || self.class.in_rails_application_subdirectory?

  if self.class.in_rails_application?
    generate_database_yml!
    return
  end

  Dir.chdir("..") do
    # Recurse in a chdir block: if the search fails we want to be sure
    # the application is generated in the original working directory.
    create! unless cwd == Dir.pwd
  end
rescue SystemCallError
  # could not chdir, no problem just return
end

#generate_database_yml! ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/database_yml.rb', line 47

def generate_database_yml!
  template = File.open(File.join(TEMPLATES_DIR, @database)).read
  output_file = File.new(File.join(Dir.pwd, "config", "database.yml"), "w")

  username = Etc.getlogin
  application_name = File.basename(Dir.getwd)

  template.gsub!("USERNAME", username)
  template.gsub!("APPLICATION_NAME", application_name)

  output_file.write(template)

  puts "database.yml created for #{@database}"
end