2

当我将以下行放入~/.pryrc其中时,它无法按预期工作:

Pry.config.prompt_name = Time.now.to_s

每个提示都等于 Pry 启动的时间。

每次显示提示时(每次调用后),如何使用当前时间戳更新提示?

4

2 回答 2

2

你需要使用promptprompt_name

Pry.config.prompt = Proc.new { |output, value| Time.now.to_s[0..-6] } 
于 2014-02-28T01:45:45.647 回答
2

对于发现这有用的人,我以.pryrc这种方式添加了时间戳。
留意我在代码中的注释,因为pry代码会不时发生变化,也是在提示中添加时间戳的方式:

# Unrelated, but it could be useful for you to print the current Rails env
def rails_prompt
  # Maybe this is only running as `pry` an not `rails console`, so check first
  return '' unless defined? Rails

  app_env =
    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"
      "\e[31m#{Rails.env[0...4]}\e[0m" # red
    else
      "\e[32m#{Rails.env[0...4]}\e[0m" # green
    end
  "(\e[1m#{app_env}\e[22m)" # bold
end

# This will generate a timestamp like 11:11:51NZST but change it any other
# format you're expecting
now = proc { Time.new.strftime('%T%Z') }

# This worked for me with pry 0.10.1, but probably will work with older/not so
# new versions?
# == START 0.10.1 CODE ==
def_proc = proc { |target_self, nest_level, pry|
  "[#{pry.input_array.size}][#{now.call}] "\
  "(#{Pry.view_clip(target_self)})"\
  "#{":#{nest_level}" unless nest_level.zero?}#{rails_prompt}"
}
Pry.config.prompt = [
  proc { |t, n, p| "#{def_proc.call(t, n, p)}> " },
  proc { |t, n, p| "#{def_proc.call(t, n, p)}* " }
]
# == END 0.10.1 CODE ==

# so, eventually I updated to 0.12.2 and I had to change stuff. This will be the
# proc to be called to evaluate the current prompt status
custom_prompt = proc { |context, nesting, pry_instance, sep|
  format(
    's[%<in_count>s][%<timestamp>s] %<name>s(%<context>s)%<rails_prompt>s%<nesting>s%<separator>s ',
    in_count: pry_instance.input_ring.count,
    timestamp: now.call,
    name: pry_instance.config.prompt_name,
    context: Pry.view_clip(context),
    rails_prompt: rails_prompt,
    nesting: (nesting > 0 ? ":#{nesting}" : ''),
    separator: sep
  )
}

# == START 0.12.2 CODE ==
Pry::Prompt.add(:default_with_time, 'The same default, but with timestamp') do
  |context, nesting, pry_instance, sep|
  custom_prompt.call(context, nesting, pry_instance, sep)
end
Pry.config.prompt = Pry::Prompt[:default_with_time][:value]
# == END 0.12.2 CODE ==

# and my last update was to pry 0.14.0 and I had to tweak the code again. The
# prompt status proc is the same as in 0.12.2, but is passed as parameter in a
# different way.
Pry.config.prompt = Pry::Prompt.new(
  :default_with_time,
  'The same default, but with timestamp',
  [custom_prompt]
)

然后你会得到这样的提示: 在此处输入图像描述

作为参考,我采用了默认提示格式的一部分,并根据我的需要对其进行了调整,因此对于较新的版本可能会再次更改(或者可能不会,谁知道)。

于 2020-01-31T01:28:00.303 回答