OpenGears
OpenGears

Reputation: 142

ActiveRecord: how to share connections between AR-models when using ActiveRecord without Rails

am trying to use ActiveRecord without Rails, to create a gem that connects to a MySql database. The connection to the database should be settable, because the gem is intended mainly for console use, so I don't want to provide the database connection information beforehand in a YAML file, but provide it "on-the-fly". This seems to bring a lot of problems, since the ActiveRecord models are loading the database information on initialisation. Is there any other way of sharing the database information or some way to make active_record not preload the database configurations? Is there maybe a better way to share connection information than "establish_connection"?

here is my code:

class Blog 
  @@options = { :adapter  => "mysql2" }

  def self.options
    @@options
  end

  def initialize(options = Hash.new)
    @@options = {
      :adapter  => "mysql2",
      :host     => options[:host] || "localhost",
      :username => options[:user] || "root",
      :password => options[:pass] || "",
      :database => options[:db] || "my_blog"
    }
  end
end

module Foobar
  class Post < ActiveRecord::Base
    establish_connection(Blog.options)
  end
end

on the command line

Blog.new(user:"foo",pass:"bar",db:"bang")
p=Foobar::Post.all

Upvotes: 3

Views: 339

Answers (1)

EugZol
EugZol

Reputation: 6545

You should just call ActiveRecord::Base.establish_connection(...).

class Blog
  # No need to use initializer method if you don't intend
  # to use initialized instance. Static method will do better.
  def self.connect(options = Hash.new)
    ActiveRecord::Base.establish_connection(
      adapter:  "mysql2",
      host:     options[:host] || "localhost",
      username: options[:user] || "root",
      password: options[:pass] || "",
      database: options[:db] || "my_blog"
    )
  end
end

module Foobar
  class Post < ActiveRecord::Base
    # Connection is done via Blog model
  end
end

Blog.connect(username: 'john', password: 'qwerty')
posts = Foobar::Post.all

Upvotes: 1

Related Questions