如何在ruby中获取实例?

时间:2010-09-30 20:22:57

标签: ruby

我有这样的情况:

class Person
  #a class that wraps to some db table
  def initialize(attributes=nil)
    populate_with_attributes(attributes) if !attributes.nil?
  end
  def self.find(id)
    @the_db.execute('query here where id....')
  end
  def save
    #save logic and queries here
    @the_db.execute('save query here')
  end
  # other methods .....
end

class SuperPerson
  #another class that wraps to some db table
end

class SpTh < Thread
  def initialize(thread_id, *other_params)
    super
    @thread_id = thread_id
    @db = SQLite3.Database.new("./db_#{@thread_id}.sqlite3")
    #....
  end

  def start
    person = Person.find(55)
    person.age = 27
    person.save
  end
  # other methods .....
end

class Sp
  def initialize
    @threads_amount = 5
    @threads = []
    #...
    raise_threads
    #...
  end

  def raise_threads
    @threads_amount.times{|thread_id|
      @threads << SpTh.new(thread_id, *other_params){}
    }
  end
  # other methods .....
end

我的问题是: 如何将Person和SuperPerson类中@the_db变量的值设置为SpTh类的@db值,以便每个线程都有自己的数据库?

1 个答案:

答案 0 :(得分:2)

您正在从实例(在@the_db中)和类(在save中)访问类self.find:将它包装在类方法中,所以从实例中你可以通过调用self.class.connection在类上访问它(参见db方法):

class Person
  def self.connect(connection)
    @the_db = connection
  end

  def self.connection
    @the_db
  end

  def self.find(id)
    @the_db.execute("...")
  end

  def db
    self.class.connection
  end
end

您可以使用单例类来设置不同的连接:

db = SQLite3.Database.new("./db_#{@thread_id}.sqlite3")

person_class = Class.new(Person){ self.connect(db) }
person_class.find(1)