Search code examples
rubypromptirb

Is it possible to configure the IRB prompt to change dynamically?


I'd like to navigate around the filesystem in IRB and have the prompt change to reflect the current working directory, but I can't figure out how to make the prompt update after each command. Ultimately I'd like to use IRB in day to day work a lot more and let bash slip away. I tried this in my .irbrc:

require 'fileutils'
include FileUtils

IRB.conf[:PROMPT][:CUSTOM] = {
    :PROMPT_N => "\e[1m:\e[m ",
    :PROMPT_I => "\e[1m#{pwd} >\e[m ",
    :PROMPT_S => "FOO",
    :PROMPT_C => "\e[1m#{pwd} >\e[m ",
    :RETURN => ""
}
IRB.conf[:PROMPT_MODE] = :CUSTOM

But the IRB prompt is not updated:

julianmann@mango:~ > irb
/users/julianmann > puts pwd
/users/julianmann
/users/julianmann > cd 'dev'
/users/julianmann > puts pwd
/users/julianmann/dev
/users/julianmann > 

I'd really like the prompt to change.


Solution

  • Here's a quick hack to get the working dir. It's sort of fragile, but it worked on ruby 1.8.7 and 1.9.2.

    Set your prompt string to something like this:

    "%N(%m):%03n:%i %~> ".tap {|s| def s.dup; gsub('%~', Dir.pwd); end }
    

    The "%~" directive is not understood by irb itself, so I used it to do the replacement. This hack relies on the fact that irb calls dup to generate the prompt.