【问题标题】:undefined method 'execute' for nil:NilClassnil:NilClass 的未定义方法“执行”
【发布时间】:2018-12-11 17:53:12
【问题描述】:

我正在用 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 内部。我在这里做错了什么?提前致谢!

【问题讨论】:

  • 不是在说execute方法,而是在调用时@db变量为nil
  • 非常感谢,伙计..!!!这是一个愚蠢的错误......哈哈
  • 如果它解决了您的问题,我可以将其发布为答案,或者您可以这样做。

标签: ruby sqlite sqlite3-ruby


【解决方案1】:

问题在于动态形成的新类不知道连接变量“@db”。因此,代码解决了问题。

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

非常感谢Jagdeep Singh

【讨论】:

    猜你喜欢
    • 2011-07-27
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多