Rails (3.2.3) アプリケーションを書きました...
config/application.rb:
# ...
class MyWebApp
class Application < Rails::Application
# ...
config.before_initialize do
$my_config = MyConfig.new
end
end
end
config/database.yml:
development:
adapter: mysql2
encoding: utf8
reconnect: true
database: <%=$my_config.config['db']['basename']%>_development
pool: 5
username: <%=$my_config.config['db']['username']%>
password:
socket: /var/run/mysqld/mysqld.sock
次に、 rake db:create は以下を発生させます:
rake aborted!
undefined method `config' for nil:NilClass
(erb):15:in `<main>'
/home/sn/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/erb.rb:838:in `eval'
/home/sn/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/erb.rb:838:in `result'
/home/sn/dev/mywebapp/vendor/bundle/ruby/1.9.1/gems/railties-3.2.3/lib/rails/application/configuration.rb:115:in `database_configuration'
...
データベースを手動で作成した後、rake db:migrate は成功します。だから私はdatabases.rakeを読んで、db:migrateは:environmentタスクを呼び出しますが、db:createは呼び出しません。
activerecord-3.2.3/lib/active_record/railties/databases.rake:
task :create => :load_config do
configs_for_environment.each { |config| create_database(config) }
ActiveRecord::Base.establish_connection(configs_for_environment.first)
end
task :migrate => [:environment, :load_config] do
ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil) do |migration|
ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope)
end
end
rake db:create で $my_config 変数を正しく初期化する簡単な方法を知っていますか?