Can you get DB username, pw, database name in Rails?

前端 未结 5 1892
感动是毒
感动是毒 2020-12-12 11:54

I\'m writing a rake task that does some DB work outside of Rails/ActiveRecord.

Is there a way to get the DB connection info (host, username, password, DB name) for t

5条回答
  •  暖寄归人
    2020-12-12 12:10

    Old question but this was one of my first stops in looking up how to do this so I figure this may help someone else. I normally have .my.cnf files in the home directory. So using the 'parseconfig' gem and some ERB syntax in my database.yml config file means I've got dynamic file that I can feel good about checking into source control and also simplify deployments (in my case). Also note the list of common sockets, this makes it easier to move my app to different operating systems that might have a different Unix socket path.

    <% 
        require 'parseconfig'
        c=ParseConfig.new('../../.my.cnf') %>
    
    mysqlevn: &mysql
      adapter: mysql 
      username: <%= c.params['client']['user'] %>
      password: <%= c.params['client']['password'] %>
      host: localhost 
      socket: <%= [ 
      '/var/run/mysqld/mysqld.sock',
      '/var/lib/mysql/mysql.sock',
      '/tmp/mysqld.sock',
      '/tmp/mysql.sock'].detect { |socket| File.exist?(socket) } %>
    
    production:
      database: app_production
      <<: *mysql
    
    
    development:
      database: app_development 
      <<: *mysql
    
    # Do not set this db to the same as development or production.
    test:
      database: app_test
      <<: *mysql
    

    ref: http://effectif.com/articles/database-yml-should-be-checked-in

提交回复
热议问题