如何在ruby中获取实例?

如何在ruby中获取实例?,ruby,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

我有这样一个案例:

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
班级人员
#包装到某个db表的类
def初始化(属性=nil)
如果需要,用_属性(属性)填充_!零?
结束
def自我查找(id)
@_db.execute('query here where id…')
结束
def保存
#在此处保存逻辑和查询
@_db.execute('save query here')
结束
#其他方法。。。。。
结束
班长
#另一个封装到某个db表的类
结束
SpTh级<螺纹
def初始化(线程id,*其他参数)
超级的
@线程id=线程id
@db=SQLite3.Database.new(“./db_3;{@thread_id}.SQLite3”)
#....
结束
def启动
person=person.find(55)
个人年龄=27
个人拯救
结束
#其他方法。。。。。
结束
类Sp
def初始化
@线程数量=5
@线程=[]
#...
提升螺纹
#...
结束
def raise_螺纹
@线程数量.乘以{124;线程id|

@线程您正在从实例(在
save
中)和类(在
self.find
中)访问类的
@db
:将其包装在一个类方法中,这样您就可以通过调用
self.class.connection
在类上访问它(参见db方法):

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

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

person_class = Class.new(Person){ self.connect(db) }
person_class.find(1)
db = SQLite3.Database.new("./db_#{@thread_id}.sqlite3")

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