How can I load ActiveRecord on an IRB session?
I have the following
# config/app.rb
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'db/mydb.sqlite3'
)
But when I start IRB and try to load it
irb#1(main):001:0> require config/application.rb
I get
NameError: undefined local variable or method `config' for main:Object
Did you mean? conf
I'd like to be able to interact with my ActiveRecord objects from IRB. I'm NOT using Rails but only ActiveRecord.
Thanks
Two things to change here:
- Always put quotes around the path you're requiring. The reason Ruby is saying "undefined local variable or method" is that it's trying to interpret
configas a variable name. Put the name in quotes and it won't. - Use
require_relativewhen loading files that are part of your application.requireonly looks in the default Ruby load paths.
Try this:
require_relative 'config/application.rb'
You can use pry to build a console started from command line. Simple console solution below. This way you don't have to require in irb every time you stare interactive session.
# bin/console
#!/usr/bin/env ruby
require_relative '../config/app.rb'
require 'pry'
binding.pry
More about pry https://github.com/pry/pry
P.S. You should set +x on bin/console, i.e.
$ chmod +x bin/console
Then you just call
$ bin/console
and get all the code run from config/app.rb and interactive session ready. No need to require anything from irb to start working.
Poor-man's rails console equiv. :-)
来源:https://stackoverflow.com/questions/39694428/requiring-activerecord-on-irb-ruby-no-rails