nil:NilClass 的未定义方法 'execute'

undefined method 'execute' for nil:NilClass

我正在 ruby 制作一个可以与数据库交互的工具。 我正在使用 amalgalite 作为 sqlite3 的适配器。

代码:

require 'amalgalite'
# this is class RQuery
class RQuery
  def db_open(db_name)
    @db = Amalgalite::Database.new "#{db_name}.db"
    make_class
  end

  def exec_this(query)
    @db.execute(query)
  end

  def make_class
    tables_list = exec_this("select name from sqlite_master where type='table'")
    tables_list.each do |table|
      @class_created = Object.const_set(table[0].capitalize, Class.new)
      @class_created.class_eval do
        define_singleton_method :first do
          RQuery.new.exec_this("select * from #{table[0]} order by #{table[0]}.id ASC limit 1")
        end
      end
    end
  end

  def eval_this(input)
    instance_eval(input)
  end

  def code
    print '>>'
    input = gets
    exit if input =~ /^q$/
    puts eval_this(input)
    code
  end
end

现在,当我 运行 时,代码一切正常,直到我调用 table_name.first

它给出输出

vbhv@fsociety ~/git/R-Query/bin $ ruby main.rb 
Enter the code or q for quit
>>db_open('vbhv')
users
persons
people
programmers
>>Users.first
/home/vbhv/git/R-Query/lib/r-query.rb:36:in `instance_eval': undefined  method `execute' for nil:NilClass (NoMethodError)
Did you mean?  exec
from /home/vbhv/git/R-Query/lib/r-query.rb:29:in `block (3 levels) in make_class'
from (eval):1:in `eval_this'
from /home/vbhv/git/R-Query/lib/r-query.rb:36:in `instance_eval'
from /home/vbhv/git/R-Query/lib/r-query.rb:36:in `eval_this'
from /home/vbhv/git/R-Query/lib/r-query.rb:43:in `code'
from /home/vbhv/git/R-Query/lib/r-query.rb:44:in `code'
from /home/vbhv/git/R-Query/lib/r-query.rb:44:in `code'
from main.rb:4:in `<main>'

现在它所说的 'execute' 函数在 amalgalite 里面。我在这里做错了什么?提前致谢!

这里的问题是动态形成的新 class 不知道连接变量“@db”。因此代码解决了这个问题。

@class_created.instance_variable_set(:@database, @db)

非常感谢Jagdeep Singh