rubysqlitesqlite3-ruby

undefined method 'execute' for nil:NilClass


I am making a tool in ruby which can interact with databases. I am using amalgalite as an adapter for sqlite3.

Code:

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

Now when I am running the code everything works fine until I call table_name.first

It gives output

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>'

Now the 'execute' function it is talking about is inside amalgalite. What am I doing wrong here?? Thanks in Advance!


Solution

  • The problem in this was that the new class formed dynamically doesn't know about the connection variable '@db'. Hence the code solves the problem.

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

    A big thanks to Jagdeep Singh.