Reload rubygems in irb? - ruby

I've this script right now.
def r(this)
require this
puts "#{this} is now loaded."
rescue LoadError
puts "The gem '#{this}' is missing."
puts "Should I install it? [y/n]"
data = gets
if data =~ /yes|y/i
puts "Installing #{this}, hold on."
if `gem install #{this}` =~ /Successfully/i
load this
end
else
puts "Okey, goodbye."
end
end
That makes it possible to require libs on the fly.
Like this: r "haml".
The problem is that I can't load the gem after it has been installed.
Using load this or load File.expand_path("~/.irbrc") does not work.
Here is an example.
>> r "absolutize"
The gem 'absolutize' is missing.
Should I install it? [y/n]
y
Installing absolutize, hold on
LoadError: no such file to load -- absolutize
>> require "absolutize"
LoadError: no such file to load -- absolutize
>> exit
$ irb
>> require "absolutize"
=> true
Is there a way to reload rubygems or irb on the fly?

I did not try, but I think you might be looking for Gem.clear_paths
Reset the dir and path values. The next time dir or path is requested, the values will be calculated from scratch. This is mainly used by the unit tests to provide test isolation.

You can reset irb by calling exec('irb')

Just remove the file from ´$"´:
require 'erb' # Loaded.
require 'erb' # Does nothing.
$".delete_if {|e| e =~ /erb\.(?:rb|so)/} # Remove "erb" from loaded libraies.
require 'erb' # Reloaded (with warnings if the first require was successful).
See http://www.zenspider.com/Languages/Ruby/QuickRef.html#19

Related

require not working on ruby 2.0?

I'm doing a test with "require" under ruby 2.0.0p576 (2014-09-19 revision 47628) [x86_64-darwin13.4.0] it doesn't work in many ways.
There are two files in ruby directory as shown below:
string_extensions.rb
class String
def vowels
self.scan(/[aeiou]/i)
end
end
vowels_test.rb
require 'string_extensions'
puts "This is a test".vowels.join('-')
fire up IRB
Snailwalkers-MacBook-Pro:ruby snailwalker$ ruby vowels_test.rb
returs : `require': cannot load such file -- string_extensions (LoadError)
I tried to change require 'string_extensions' to " require_relative 'string_extensions' ; require './string_extensions.rb' . They all didn't work.
both return error : vowels_test.rb:1:in require_relative': /Users/snailwalker/Ruby/string_extensions.rb:1: class/module name must be CONSTANT (SyntaxError)
Your help will be greatly appreciated!
You can use require_relative instead:
require_relative 'string_extensions'
puts "This is a test".vowels.join('-')
Or even require './string_extensions'.
Use:
ruby -I. vowels_test.rb
Automatic inclusion of the current directory in the load paths was removed in Ruby 2.

locating "irbrc" file on a Mac

I see a lot of cool stuff I can add to my Ruby console. For example, a good list is
"My .irbrc for console/irb".
I googled, but all I found is weblogs saying what gems people add to their .irbrc. No one is saying where to find it.
I cannot find "irbrc".
I opened my home folder and, if I type IRB, it goes to the Ruby console, but I can't find this file.
Can someone help me locate it?
It's a irbrc dotfile so you will need to ls -a in your home directory to find it. If it isn't in there, simply create a .irbrc file.
Mine's pretty simple but this is what I have in it:
require 'rubygems'
require 'ap'
require 'irb/completion'
ARGV.concat [ "--readline", "--prompt-mode", "simple" ]
module Readline
module History
LOG = "#{ENV['HOME']}/.irb-history"
def self.write_log(line)
File.open(LOG, 'ab') {|f| f << "#{line}\n"}
end
def self.start_session_log
write_log("\n# session start: #{Time.now}\n\n")
at_exit { write_log("\n# session stop: #{Time.now}\n") }
end
end
alias :old_readline :readline
def readline(*args)
ln = old_readline(*args)
begin
History.write_log(ln)
rescue
end
ln
end
end
IRB::Irb.class_eval do
def output_value
ap #context.last_value
end
end
Readline::History.start_session_log
require 'irb/ext/save-history'
IRB.conf[:SAVE_HISTORY] = 100
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"
IRB.conf[:PROMPT_MODE] = :SIMPLE
require 'irb/completion'
If you are unable to find the file.irbrc in your home directory, simply create it in your home directory and fill it with some lines such as:
require "irb/completion"
Then your irb will automatically load completion module when you launch irb.
PS: it also works for UNIX/Linux system.

Can I conditionally skip loading "further" ruby code in the same file?

Can I conditionally skip loading "further" ruby code in the same file,
if a library (loaded via require) is not found ?
begin
require 'aws-sdk'
rescue LoadError
puts "aws-sdk gem not found"
return #does not work. nor does next
end
# code after here should not be executed as `aws-sdk` gem was not found
puts "=== should not get executed"
namespace :db do
desc "import local postgres database to heroku. user and database name is hardcoded"
task :import_to_heroku => [:environment, "db:dump_for_heroku"] do
# code using aws-sdk gem
end
end
In the above code, can I ask Ruby not to load the file further after
hitting a rescue LoadError.
Like an early return but for loading a file and not for a function.
Need it because i have i have a rake task which needs aws-sdk rubygem but i use it only
on my local machine. If aws-sdk is not found it does not make sense for me to load code afterwards in the same file. I guess i can split the code into smaller files and warp it in
a require call
if Rails.env.development?
require 'import_to_heroku'
end
But do not want to warp or modify my existing code
Also, i can wrap the whole code in an conditional but that is inelegant.
A begin-rescue block is also a form of explicit control flow.
I do not want to wrap or touch the original code is any manner
Maybe an api such as
require_or_skip_further_loading 'aws-ruby`
So i want my code to be functionally equivalent to
begin
require 'aws-sdk'
namespace :db do
desc "import local postgres database to heroku. user and database name is hardcoded"
task :import_to_heroku => [:environment, "db:dump_for_heroku"] do
# code using aws-sdk gem
end
end
rescue LoadError
puts "aws-sdk gem not found"
end
Or via an if conditional
library_found = false
begin
require 'aws-sdk'
library_found = true
rescue LoadError
puts "aws-sdk gem not found"
return #does not work
end
if library_found
namespace :db do
desc "import local postgres database to heroku. user and database name is hardcoded"
task :import_to_heroku => [:environment, "db:dump_for_heroku"] do
# code using aws-sdk gem
end
end
end
Want program execution to continue after LoadError is raised. ie. gracefully handle LoadError and do not load code written after LoadError in the same file. cannot raise exit or abort on LoadError And particularly the code after LoadError should not be executed (or loaded) by the ruby interpreter
Had originally asked How to skip require in ruby?
but i did not ask the question properly. hope this is better worded
I haven't checked the source, but I suppose that, when you run ruby my_file.rb at the console, or require/load it from Ruby code, the file is read entirely into memory before being evaluated. I'm afraid there is no such thing as skipping a part of a file.
I had an idea with catch/throw.
requiring file (for example a Rake task ?) treq1.rb :
catch :aws_sdk do
require_relative 'original'
end
puts '... continued'
The original file that you don't want to modify, original.rb :
puts 'in original, not to be modified'
begin
require 'aws-sdk'
rescue LoadError
puts "aws-sdk gem not found"
throw :aws_sdk
end
puts ">>> to execute only if 'aws-sdk' is found"
# namespace :db do ... etc
#end
Execution :
$ ruby -w treq1.rb
in original, not to be modified
aws-sdk gem not found
treq1.rb:2:in `require_relative': method `backtrace' called on unexpected T_NODE object (0x007fd32b88e900 flags=0x381c klass=0x0) (NotImplementedError)
from treq1.rb:2:in `block in <main>'
from treq1.rb:1:in `catch'
from treq1.rb:1:in `<main>'
Googling with the error : http://www.ruby-forum.com/topic/4406870
Recent post, no answer. It works in a single file, if you want to wrap your code.
Let's try another solution. Supposing that you can change the Rake task, treq2.rb :
begin
require_relative 'original'
rescue LocalJumpError
puts 'rescued LocalJumpError'
end
puts '... continued'
In original.rb, replace throw :aws_sdk by return :
$ ruby -w treq2.rb
in original, not to be modified
aws-sdk gem not found
rescued LocalJumpError
... continued
This way it works.
HTH
The "top-level return" feature has been added.
It is now possible to use the return keyword at the top level, as in your "via an if conditional" example. Further discussion here.

create ruby definition on irb load

I would like to have a clear function in my irb console, but there isn't one. Here's what I type in every time I load irb from the terminal:
def cls
system 'clear'
end
It's not real hard to type this each time a load irb, but it would certainly be nice to have this function load automatically when irb starts.
Is it possible to do this?
When irb is starting up, it looks for the file .irbrc in your home directory. If the file exists, it evaluates it. So this file is the perfect place to add some generic stuff to irb...
For inspiration, mine looks like this:
require 'rubygems'
require 'pp'
require 'irb/ext/save-history'
# add $HOME/lib to the load path
$: << '~/lib'
IRB.conf[:AUTO_INDENT] = true
IRB.conf[:SAVE_HISTORY] = 1000
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb_history"
def real_instance_methods_of(klass)
klass.instance_methods - ((klass.ancestors - [klass]).map(&:instance_methods).flatten)
end
class Class
def instance_methods_defined_here
real_instance_methods_of self
end
end
# more stuff...
# ...
EDIT: I just noticed the comment by Dave Newton now; he already pointed out the .irbrc solution...
on a mac just hit CMD + K to clear the screen

irb history not working

in ~/.irbrc i have these lines:
require 'irb/ext/save-history'
#History configuration
IRB.conf[:SAVE_HISTORY] = 100
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"
and yet when i run irb and hit the up arrow nothing happens. also the irb history file specified is not getting created and nothing is logged to it.
irb history works in Debian Linux out of the box. There's no etc/irbrc, nor do I have a ~/.irbrc. So, hmmmm.
This person put a bit more in his irbrc than you did. Do you suppose the ARGV.concat could be the missing piece?
require 'irb/completion'
require 'irb/ext/save-history'
ARGV.concat [ "--readline", "--prompt-mode", "simple" ]
IRB.conf[:SAVE_HISTORY] = 100
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"
I don't have an answer for you why the above doesn't work, but I did find a file, /etc/irbrc on my system (OS X - Snow Leopard, Ruby 1.8.7) that does provide a working, persistent history for me. So two pieces of advice: i) check your /etc/irbrc (or equivalent) to make sure that there isn't anything in there that might interfere with your settings, and ii) try out the settings below to see if you can get history working that way.
# Some default enhancements/settings for IRB, based on
# http://wiki.rubygarden.org/Ruby/page/show/Irb/TipsAndTricks
unless defined? ETC_IRBRC_LOADED
# Require RubyGems by default.
require 'rubygems'
# Activate auto-completion.
require 'irb/completion'
# Use the simple prompt if possible.
IRB.conf[:PROMPT_MODE] = :SIMPLE if IRB.conf[:PROMPT_MODE] == :DEFAULT
# Setup permanent history.
HISTFILE = "~/.irb_history"
MAXHISTSIZE = 100
begin
histfile = File::expand_path(HISTFILE)
if File::exists?(histfile)
lines = IO::readlines(histfile).collect { |line| line.chomp }
puts "Read #{lines.nitems} saved history commands from '#{histfile}'." if $VERBOSE
Readline::HISTORY.push(*lines)
else
puts "History file '#{histfile}' was empty or non-existant." if $VERBOSE
end
Kernel::at_exit do
lines = Readline::HISTORY.to_a.reverse.uniq.reverse
lines = lines[-MAXHISTSIZE, MAXHISTSIZE] if lines.nitems > MAXHISTSIZE
puts "Saving #{lines.length} history lines to '#{histfile}'." if $VERBOSE
File::open(histfile, File::WRONLY|File::CREAT|File::TRUNC) { |io| io.puts lines.join("\n") }
end
rescue => e
puts "Error when configuring permanent history: #{e}" if $VERBOSE
end
ETC_IRBRC_LOADED=true
end
This is a known bug with a patch available. Easiest solution is to overwrite save-history.rb:
/usr/lib/ruby/1.8/irb/ext/save-history.rb
with a fixed version:
http://pastie.org/513500
or to do it in one go:
wget -O /usr/lib/ruby/1.8/irb/ext/save-history.rb http://pastie.org/pastes/513500/download
Check to make sure you built ruby with libreadline as irb history seems to not work without it.
This may also happen if you have extra irb config file, e.g. ~/.irbrc. If this is the case, copy the content from liwp's answer to the extra config and it should work.
I had the same problem on ubuntu 20.04 and fixed it by running:
gem install irb

Resources