Accessing the irb in a modular Sinatra application

2020-06-30 04:31发布

I am building an application which subclasses Sinatra like so:

require 'rubygems'
require 'sinatra/base'
require 'sinatra/assetpack'

class App < Sinatra::Base
  ...

  run!
end

How can I access irb? Options are not parsed when executing sinatra this way, how do I programmatically open an irb shell?

标签: ruby sinatra irb
3条回答
Viruses.
2楼-- · 2020-06-30 04:45

I'm a little confused whether you want to open an IRB session from within your app (?) or use IRB to debug your Sinatra project?

For debugging Rack-based apps (such as Sinatra), I like using the racksh gem, which "is like script/console in Rails" for Rack applications. Its main advantage over IRB is that racksh loads the entire application environment into the shell, making debugging a breeze.

From racksh's Github page: "It's purpose is to allow developer to introspect his application and/or make some initial setup. You can for example run DataMapper.auto_migrate! or make a request to /users/666 and check response details. It's mainly aimed at apps that don't have console-like component (ie. apps built with Sinatra) but all frameworks can benefit from interactive Rack stack and request introspection."

However, racksh requires your app to have a config.ru file, so you would have to re-write your app:

# in config.ru
require 'rubygems'
require 'sinatra/base'
require 'sinatra/assetpack'
require 'app.rb'


# in app.rb
class App < Sinatra::Base
  ...

  run!
end

Then in your app folder (where config.ru resides):

$ gem install racksh # or add gem 'racksh' to your Gemfile and run bundle
$ racksh
查看更多
淡お忘
3楼-- · 2020-06-30 04:50

Check this simple search interface for Microsoft's Bing using Sinatra and binger gem. If you follow the instructions from there you will understand better.

First at all, create a Gemfile and add:

source "https://rubygems.org"

gem 'sinatra'
gem 'binger'

Then run the bundle command that will generated Gemfile.lock. Then create a config.ru file, and add by example:

require 'rubygems'
require 'bundler'

Bundler.require

require './app.rb'

run MyApp

Your app.rb could look like this:

class MyApp < Sinatra::Base

  get '/' do

      @title = "Index" 

      erb:index

  end
end

You must have a folder named views. Create index.erb and add:

< % = @title % >

Finally, run rackup.

Source: https://github.com/thinkphp/sinatra-bing

Demo: http://sinatra-bing.herokuapp.com/

查看更多
▲ chillily
4楼-- · 2020-06-30 04:51

Just type as below (at the shell prompt):

irb -r ./my_app.rb
查看更多
登录 后发表回答