Ruby - create gem: reload console with updated gem content

。_饼干妹妹 提交于 2019-12-21 09:22:14

问题


According to this article, we can test around our gem code by adding those lines to our rakefile:

task :console do
  require 'irb'
  require 'irb/completion'
  require 'my_gem' # You know what to do.
  ARGV.clear
  IRB.start
end

It works really well, except that whenever a change is made to the gem, I need to exit and rerun rake console to get the code updated. It is really not convenient as a creation/debugging tool ...

Is there a way to write a custom method that would act as the awesome reload! method from Rails?

A bash script won't work as the first command is in the Ruby console, and I'd rather have a 100% ruby solution.

Thanks!


回答1:


You can use the $LOADED_FEATURES global to find the components of your gem and re-load them using the load command (using require won't work, as it skips items that Ruby has already processed):

task :console do
  require 'irb'
  require 'irb/completion'
  require 'my_gem' # You know what to do.

  def reload!
    # Change 'my_gem' here too:
    files = $LOADED_FEATURES.select { |feat| feat =~ /\/my_gem\// }
    files.each { |file| load file }
  end

  ARGV.clear
  IRB.start
end

Note this will fail if you are writing native extensions, you'll have to exclude them, and you'll want a compile step and to exit/re-start anyway if they change.



来源:https://stackoverflow.com/questions/23675616/ruby-create-gem-reload-console-with-updated-gem-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!