麻烦传递多余的论点

时间:2014-10-01 12:15:13

标签: ruby sqlite

我有SQLite3 gem,我只能为数据库初始化一次。假设我method1调用method2十次,调用method3二十次,这需要访问SQLite数据库并更新一些记录。如果我在method3内初始化它,我最终会得到100多个SQLite3实例。 Method1,method2和method3都属于不同的类。

我通过在顶层创建新实例,然后将其传递到method1,然后传递到method2method3来解决它。这是不可持续的,因为如果我使用两个或三个以上的参数(比如我还有三个method3将更新的数据库),那么会有很多冗余参数。

我该如何解决这个问题?一些想法正在创建一个全局变量或一个常量,它将在程序初始化时开始。另一个,覆盖new方法。我不知道每个的优点和缺点。如果你知道其他方法,或者上述两种方法的优点/缺点/可行性,请告诉我。

这是一个示例代码:

require 'sqlite3'

class A
  db = SQLite3::Database.new('somename.sqlite')

  def call_other_method
    B.new.other_method
  end
end

class B
  def other_method
    C.new.other_method_2
  end
end

class C
  def other_method_2
    # I want to call here methods on db, without passing it as an arg, first 
    # to call_other_method, then to other_method and then to other_method_2
  end
end

A.new.call_other_method

1 个答案:

答案 0 :(得分:0)

一种方法可能是:

module Sqlite3Connection
  require 'sqlite3'

  def self.connection
    @@db ||= SQLite3::Database.new('somename.sqlite')
  end
end

require 'sqlite3_connection'
class SQLite3Record
  include Sqlite3Connection

  attr_reader :db

  def initialize
    @db = SQLite3Connection.connection
  end

end

class A < SQLite3Record

  def call_other_method
    # did you mean this?:
    10.times{ B.new.other_method }
    # or?:
    # b = B.new
    # 10.times { b.other_method }
  end
end

class B < SQLite3Record

  def other_method
    # did you mean this?:
    20.times{ C.new.other_method_2 }
    # or?:
    # c = C.new
    # 20.times { c.other_method2 }
  end
end

class C < SQLite3Record

  def other_method_2
    # will be called 200 times!
    # will have single instance of "SQLite3::Database" here accessible via method db.
    db.execute(sql)
  end
end

A.new.call_other_method
相关问题