新手问题 script/console for your application (老帖)

i5ting · 2013年06月19日 · 最后由 i5ting 回复于 2013年06月19日 · 2043 次阅读

http://barkingiguana.com/2009/01/25/scriptconsole-for-your-application/

了解这个比看 rails 源码更简单

script/console for your application

Rails coders will be more than familiar with the script/console command. It fires up a session in which you can interact with your application through the models that you've built. It's invaluable for debugging problems and can be really useful when building or administering the application. Not all of our Ruby applications are Rails applications though. Wouldn't it be nice to have a script/console anyway?

Turns out it's really easy to build one. Here's how.

First, decide on the libraries and files you'd like to have loaded. This almost always includes RubyGems and an init file from your application. I usually store the init file in config/boot.rb.

An example boot.rb could look something like this:

require 'rubygems'
require 'hpricot'
require 'net/http'
require File.dirname(__FILE__) + '/../vendor/gems/activecouch/init'

$: << File.dirname(__FILE__) + '/../app/models'

ActiveCouch::Base.class_eval do
  set_database_name 'blog'
  site 'http://localhost:5984/'
end

require 'article'
require 'comment'
require 'author'

Once we have these files we can create a Ruby script that'll run IRb, require the files, and set the prompt to something nice and simple. I also like to print out a welcome banner.

#! /usr/bin/env ruby

libs = []
libs << "irb/completion"
libs << File.dirname(__FILE__) + '/../config/boot.rb'

command_line = []
command_line << "irb"
command_line << libs.inject("") { |acc, lib| acc + %( -r "#{lib}") }
command_line << "--simple-prompt"
command = command_line.join(" ")

puts "Welcome to the <APPLICATION NAME> console interface."
exec command

I'd usually whack that code in script/console, make it chmod +x and commit it to the source code repository. Bam, instant application console.

Craig 25 Jan 2009

Craig 的博客里还有挺多好东西呢

debugging-javascript-with-a-stacktrace good

需要 登录 后方可回复, 如果你还没有账号请 注册新账号