Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 加载gem后如何重写方法/属性?_Ruby_Rubygems - Fatal编程技术网

Ruby 加载gem后如何重写方法/属性?

Ruby 加载gem后如何重写方法/属性?,ruby,rubygems,Ruby,Rubygems,我正在开发一个覆盖Pry.config.print方法的gem。这是执行此操作的代码: if !!defined?(::Pry) puts 'Working with Pry' Pry.config.print = proc do |output, value| if value.class.included_modules.include?(::Organizer::Explainer) output.puts "#{value.inspect}" els

我正在开发一个覆盖
Pry.config.print
方法的gem。这是执行此操作的代码:

if !!defined?(::Pry)
  puts 'Working with Pry'

  Pry.config.print = proc do |output, value|
    if value.class.included_modules.include?(::Organizer::Explainer)
      output.puts "#{value.inspect}"
    else
      ::Pry::DEFAULT_PRINT.call(output, value, _pry_)
    end
  end

else
  puts 'Not working with Pry'
end
我将我的gem包含在一个rails项目中,在执行
rails c
之后,我可以看到消息:“不使用Pry”。 然后,我在控制台中复制/粘贴前面的代码,我可以看到消息:“使用Pry”,并且所有操作都很好


所以,问题是,我需要在pry加载后执行de代码。我该怎么做呢?

Rails在开发过程中运行缓慢,因此在您的
Rails控制台
会话中尝试使用
Pry
之前,它不会被加载。听起来好像第一次运行代码时,没有任何东西访问了
Pry
,但到了第二次,有些东西已经访问了

为了确保在您尝试使用或monkeypatch之前加载库,特别是如果您正在开发一个可以在Rails外部使用的gem,其中加载必须更加明确,只需要它。所以在这种情况下,

require 'pry'
您可以用一个干净的IRB会话来说明这一点:

$ irb
2.3.0 :001 > defined?(Pry)
 => nil
2.3.0 :002 > require 'pry'
 => true
2.3.0 :003 > defined?(Pry)
 => "constant"

您是否尝试过monkey patching?)如果您的代码在替换方法之前需要pry,那么您的代码将始终在pry已加载后运行。