Class: ActiveWrapper::Db

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Db

Returns a new instance of Db.



6
7
8
9
# File 'lib/active_wrapper/db.rb', line 6

def initialize(options)
  @base = options[:base]
  @env = options[:env]
end

Instance Attribute Details

#baseObject (readonly)

Returns the value of attribute base.



4
5
6
# File 'lib/active_wrapper/db.rb', line 4

def base
  @base
end

#envObject (readonly)

Returns the value of attribute env.



4
5
6
# File 'lib/active_wrapper/db.rb', line 4

def env
  @env
end

Instance Method Details

#establish_connectionObject



11
12
13
14
15
16
17
# File 'lib/active_wrapper/db.rb', line 11

def establish_connection
  unless ActiveRecord::Base.connected?
    config = YAML::load(File.open("#{base}/config/database.yml"))
    ActiveRecord::Base.configurations = config
    ActiveRecord::Base.establish_connection(env)
  end
end

#generate_migration(name = nil) ⇒ Object



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
# File 'lib/active_wrapper/db.rb', line 28

def generate_migration(name=nil)
  raise "Please specify desired migration name with NAME=my_migration_name" unless name
  
  migration_name = name.strip.chomp
  migrations_path = "#{base}/db/migrate"
  migrations_template = File.expand_path("#{File.dirname(__FILE__)}/../../resources/migration.template")
  
  # Find the highest existing migration version or set to 1
  if (existing_migrations = Dir[File.join(migrations_path, '*.rb')]).length > 0
    version = File.basename(existing_migrations.sort.reverse.first)[/^(\d+)_/,1].to_i + 1
  else
    version = 1
  end
  
  # Read the contents of the migration template into string
  migrations_template = File.read(migrations_template)
  
  # Replace the migration name in template with the acutal one
  migration_content = migrations_template.gsub('__migration_name__', migration_name.camelize)
  migration_content = migration_content.gsub('__migration_table__', migration_name)
  
  # Generate migration filename
  migration_filename = "#{"%03d" % version}_#{migration_name}.rb"
  
  # Write the migration
  File.open(File.join(migrations_path, migration_filename), "w+") do |migration|
    migration.puts migration_content
  end
  
  # Done!
  puts "Successfully created migration #{migration_filename}"
end

#migrate(version = nil) ⇒ Object



19
20
21
# File 'lib/active_wrapper/db.rb', line 19

def migrate(version=nil)
  ActiveRecord::Migrator.migrate("#{base}/db/migrate", version)
end

#migrate_resetObject



23
24
25
26
# File 'lib/active_wrapper/db.rb', line 23

def migrate_reset
  migrate(0)
  migrate
end