简体   繁体   English

将 Ruby Gem 连接到 Rails 数据库

[英]Connect Ruby Gem to Rails database

I'm modifying a Ruby Gem to allow it to modify a Rails database via a rake task.我正在修改 Ruby Gem 以允许它通过 rake 任务修改 Rails 数据库。

I was able to connect the database and modify its content by passing the database configuration as parameters to the rake task, which then called the ActiveRecord::Base.establish_connection .通过将数据库配置作为参数传递给 rake 任务,我能够连接数据库并修改其内容,然后调用ActiveRecord::Base.establish_connection My question is, how could the Gem connect to the Rails database without having to specify the database configuration as parameters in the rake task.我的问题是,Gem 如何连接到 Rails 数据库,而不必在 rake 任务中指定数据库配置作为参数。

Assuming the gem has access to the Rails.application , you can access the database config file with假设 gem 可以访问Rails.application ,您可以访问数据库配置文件

db_config = Rails.application.config.database_configuration[Rails.env]

If it doesn't, you can parse the file yourself.如果没有,您可以自己解析文件。

db_config = YAML.load(ERB.new(File.read('./config/database.yml')).result)

Once you have your configuration, you can pass it into the connector.完成配置后,您可以将其传递给连接器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM