开发者

desktop ruby file run a script that connects with a rails application

I've use irb and console to write lots of scripts and have switched to writing single .rb files in textmate and then command+r to run it. This is really cool because I can keep all my code in one spot and just hit command+r.

So now I want it to get data from a rails app w开发者_StackOverflowhich of course has a sqlite3 database. How can I do this?


Rails includes a console, which is an IRB session pre-wired to load the models and make your DB connection, among other things. It makes it easy to do adhoc what-if's without having to manually require the needed Rails modules and perform the DB connection.

Also, Rails has a "script runner" called, amazingly enough, rails runner. It lets you run code within the context of your Rails app, without having to add the routines inside the controller or a model. It's great for utility scripts that shouldn't be part of the main app stack, but still need to access to the models and database. See rails runner -h from your Rails' app directory.

SO has some other questions about runner that might help.


I think the easiest way to access the database from outside Rails is to use the sqlite3-ruby gem. Find documentation here.

Here is some example code copied from the link above on GitHub:

require "sqlite3"

# Open a database
db = SQLite3::Database.new "test.db"

# Find a few rows
db.execute( "select * from numbers" ) do |row|
  p row
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜