Ruby - create gem: reload console with updated gem content
Asked Answered
M

1

10

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!

Maskanonge answered 15/5, 2014 at 10:28 Comment(1)
load 'whatever_file_that_was_changed.rb'Stop
V
11

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.

Valles answered 15/5, 2014 at 12:10 Comment(1)
Added a variable to get the gem name from my_gem.gemspec: @gemname = Dir["#{Dir.pwd}/*.gemspec"].first.split('/').last.sub('.gemspec', '')Maskanonge

© 2022 - 2024 — McMap. All rights reserved.