jsmartt
jsmartt

Reputation: 1484

Enabling a console for a Ruby app

I'm trying to add a console to my Ruby cli application (much like the Rails console), but I can't seem to find a solution that does what I need:

I'd like to use pry, but I can't figure out how to disable the code context from being printed out at the start of the session. I'd like it to immediately start the session without printing anything out besides the prompt.

Here's what currently gets printed when the pry session starts:

Frame number: 0/8

From: <file_path> @ line <#> <Class>#<method>:

    71: def console
    72:   client_setup
    73:   puts "Console Connected to #{@client.url}"
    74:   puts 'HINT: The @client object is available to you'
    75: rescue StandardError => e
    76:   puts "WARNING: Couldn't connect to #{@client.url}"
    77: ensure
    78:   Pry.config.prompt = proc { "> " }
    79:   binding.pry
 => 80: end
>

Here's what I want:

>

I've also tried a few other solutions, but here's my problems with each:

Any help here would be greatly appreciated!

Upvotes: 0

Views: 1188

Answers (2)

jsmartt
jsmartt

Reputation: 1484

What I ended up doing is defining a pretty simple/empty class to bind to:

class Console
  def initialize(client)
    @client = client
  end
end

Then in my console method:

Pry.config.prompt = proc { '> ' }
Pry.plugins['stack_explorer'] && Pry.plugins['stack_explorer'].disable!
Pry.start(Console.new(@client))

Disabling the stack_explorer prevented it from printing the Frame number info, and inside the Pry session, I can access @client as expected.

Upvotes: 0

SunnyMagadan
SunnyMagadan

Reputation: 1849

We usually create a separate executable file like bin/console in our project and put there content similar to this:

#!/usr/bin/env ruby

require_relative "../application"

require "pry"
Pry.start

Where application.rb is a file which loads gems via Bundler and includes all necessary application-related files, so it will be possible to use application classes in the console.

It's easy to start your console with just ./bin/console command from your terminal.

If you need to customise the look of console then official wiki at github has enough information about this: https://github.com/pry/pry/wiki/Customization-and-configuration

Upvotes: 1

Related Questions