Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if a library/ruby-gem has been loaded?

Tags:

ruby

gem

In ruby code, how would I check what external libraries are loaded? For example,

require 'some-library' if is-loaded?('some-library')   puts "this will run" end 

or

# require 'some-library' Don't load it in here if is-loaded?('some-library')   puts "this will not run" end 

Is there a way to do this?

Note on why I need this: I'm working on boom, and on windows, it will try to include 'Win32/Console/ANSI', to enable ANSI color codes like \e[36m. What I'm trying to do is if the system is windows and 'Win32/Console/ANSI' is not loaded, it would append the color codes, so the color codes are not outputted. Here is the file.

like image 600
Neil Avatar asked Dec 08 '11 00:12

Neil


People also ask

How do I check if a ruby gem is installed?

To check if a specific version is installed, just add --version , e.g.: gem list -i compass --version 0.12.

What is require Rubygems?

require 'rubygems' will adjust the Ruby loadpath allowing you to successfully require the gems you installed through rubygems, without getting a LoadError: no such file to load -- sinatra .

What is a library in Ruby?

As with most programming languages, Ruby leverages a wide set of third-party libraries. Nearly all of these libraries are released in the form of a gem, a packaged library or application that can be installed with a tool called RubyGems.


2 Answers

Most libraries will typically define a top-level constant. The usual thing to do is to check whether that constant is defined.

> defined?(CSV) #=> nil  > require "csv" #=> true  > defined?(CSV) #=> "constant"  > puts "loaded!" if defined?(CSV) loaded! #=> nil 
like image 104
yfeldblum Avatar answered Sep 19 '22 03:09

yfeldblum


require will throw a LoadError if it can't find the library you are trying to load. So you can check it like this

begin   require 'some-library'   puts 'This will run.' rescue LoadError   puts 'This will not run'   # error handling code here end 
like image 36
declan Avatar answered Sep 19 '22 03:09

declan