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

时间:2018-07-03 12:05:27

标签: ruby sqlite sqlite3-ruby

我正在用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>'

现在,它正在谈论的“执行”功能位于amalgalite内部。我在这里做错了什么?预先感谢!

1 个答案:

答案 0 :(得分:0)

其中的问题是动态形成的新类不知道连接变量'@db'。因此,代码可以解决问题。

  

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

非常感谢Jagdeep Singh