开发者

How to get the instance in ruby?

开发者 https://www.devze.com 2023-01-18 02:31 出处:网络
I have such a case: class Person #a class that wraps to some db table def initialize(attributes=nil) populate_with_attributes(attributes) if !attributes.nil?

I have such a case:

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 he开发者_开发问答re
    @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

My problem is: How do I set the value of the @the_db variable in the Person and SuperPerson classes to the value of @db from SpTh class so that each thread has its own database?


You're accessing the class's @the_db from both the instance (in save) and the class (in self.find): wrap it in a class method, so from the instance you can access it on the class by calling self.class.connection (see the db method):

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

You can use singleton classes to set different connections:

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

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

精彩评论

暂无评论...
验证码 换一张
取 消