How to format irb command prompt

前端 未结 7 1180
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 17:40

Previously I was using Ruby 1.8 and my irb command prompt used to look like this:

Air ~: irb
>> a = 1
=> 1
>> b = 2
=> 2
>&         


        
7条回答
  •  隐瞒了意图╮
    2020-12-09 18:38

    Whoever want to add a prompt timestamp, this isn't possible yet (check "special strings" section), so I implemented it in a monkey-patchy way:

    module IrbTimePrompt
      def prompt(prompt, ltype, indent, line_no)
        # I used %T as time format, but you could use whatever you want to.
        # Check https://apidock.com/ruby/Time/strftime for more options
        p = prompt.dup.gsub(/%t/, Time.new.strftime('%T'))
        super(p, ltype, indent, line_no)
      end
    end
    
    module IRB
      class Irb
        prepend IrbTimePrompt
      end
    end
    

    Now, add this to your lib/ project folder (in case is a Rails project, ensure lib/ is part of config.autoload_paths in config/application.rb) or in a more aggresive way (not recommended), look for lib/irb.rb file in your local ruby instance and in def prompt method, add a new when condition to the method, like:

        when "t"
          Time.now.strftime('%-d-%-m %T%Z')
    

    then in your .irbrc file (it could be located in your home folder or root project folder) you could modify your prompt. I'm adding my current prompt, but please adjust it to your needs:

    def rails_prompt
      # This is my base prompt, displaying line number and time
      def_prompt = '[%01n][%t]'
      # Maybe you're only running as `irb` an not `rails console`, so check first
      # if rails is available
      if defined? Rails
        app_env = Rails.env[0...4]
        if Rails.env.production?
          puts "\n\e[1m\e[41mWARNING: YOU ARE USING RAILS CONSOLE IN PRODUCTION!\n" \
               "Changing data can cause serious data loss.\n" \
               "Make sure you know what you're doing.\e[0m\e[22m\n\n"
          app_env = "\e[31m#{app_env}\e[0m" # red
        else
          app_env = "\e[32m#{app_env}\e[0m" # green
        end
        def_prompt << "(\e[1m#{app_env}\e[22m)" # bold
      end
    
      IRB.conf[:PROMPT] ||= {}
      IRB.conf[:PROMPT][:WITH_TIME] = {
        PROMPT_I: "#{def_prompt}> ",
        PROMPT_N: "#{def_prompt}| ",
        PROMPT_C: "#{def_prompt}| ",
        PROMPT_S: "#{def_prompt}%l ",
        RETURN: "=> %s\n",
        AUTO_INDENT: true,
      }
      IRB.conf[:PROMPT_MODE] = :WITH_TIME
    end
    
    rails_prompt
    

    Then start irb or rails console and check the awesomeness:

    [1][13:01:15](deve)> 'say hello to your new prompt'
    => "say hello to your new prompt"
    [2][13:01:23](deve)>
    

提交回复
热议问题