Ruby 传递多余的论点有困难
我有SQLite3 gem,对于一个数据库,我只能初始化它一次。假设我有Ruby 传递多余的论点有困难,ruby,sqlite,Ruby,Sqlite,我有SQLite3 gem,对于一个数据库,我只能初始化它一次。假设我有method1调用method2十次,调用method3二十次,需要访问SQLite数据库并更新一些记录。如果在method3中初始化SQLite3,我将得到100多个实例。Method1、method2和method3都在不同的类中 我通过在顶层创建新实例来解决这个问题,然后将其传递到method1,然后传递到method2和method3。这是不可持续的,因为如果我用两个或三个以上的参数(比如说我还有三个method3将
method1
调用method2
十次,调用method3
二十次,需要访问SQLite数据库并更新一些记录。如果在method3
中初始化SQLite3,我将得到100多个实例。Method1、method2和method3都在不同的类中
我通过在顶层创建新实例来解决这个问题,然后将其传递到method1
,然后传递到method2
和method3
。这是不可持续的,因为如果我用两个或三个以上的参数(比如说我还有三个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
一种方法可以是:
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
模块Sqlite3Connection
需要'sqlite3'
def自连接
@@db | |=SQLite3::Database.new('somename.sqlite'))
结束
结束
需要“sqlite3_连接”
类SQLite3Record
包括Sqlite3Connection
属性读取器:db
def初始化
@db=SQLite3Connection.connection
结束
结束
A类
这就是你想要的。安装ActiveRecord
gem(它可以在rails之外使用),你的生活会变得更轻松。你能发布一些你尝试过的代码来解决你的问题吗?@mudasobwa使用1个实例的好处是什么(我必须覆盖它。新建)与将一个实例存储在一个常量中,然后在需要时从中调用该常量相比,是否有理由拥有这些不同的类并从另一个类中实例化一个类?