Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - create gem: reload console with updated gem content

Tags:

ruby

gem

rakefile

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!

like image 980
Augustin Riedinger Avatar asked May 15 '14 10:05

Augustin Riedinger


People also ask

How to update Ruby gems on rails?

Updating Ruby gems is a common task you have to do as a Ruby developer. Let’s briefly discuss how to update Ruby Gems on Rails. The command below only updates the RubyGems software, not the installed gems. To upgrade a gem to a specific version, re-install the gem and specify the version number.

What is RubyGems?

In Ruby, there is a package manager called Gems. It is usually easily distributed and provides libraries to different Ruby programs. For installing Gems, RubyGems is used. Usually, Gems are installed while connected to the internet. But also, Gems can be installed Offline also.

What is must Gemfile in Ruby?

Must be inside a folder with a Gemfile. Displays a list of outdated gems in the current project. Can use the --groups option to group them. Runs an irb session with the gems from the current project's Gemfile. You've learned about RubyGems, the package system for Ruby.

How do I find the version of a gem in Ruby?

The gem version itself is defined as a constant in lib/<gem_name>/version.rb. Here’s an example gemspec: The require_paths array is where Ruby will look for your gem files when you require them.


1 Answers

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.

like image 83
Neil Slater Avatar answered Oct 26 '22 19:10

Neil Slater