Requiring ActiveRecord on IRB - Ruby (NO Rails)

浪尽此生 提交于 2019-12-08 08:17:22

问题


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


回答1:


Two things to change here:

  1. 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 config as a variable name. Put the name in quotes and it won't.
  2. Use require_relative when loading files that are part of your application. require only looks in the default Ruby load paths.

Try this:

    require_relative 'config/application.rb'



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!