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.
To check if a specific version is installed, just add --version , e.g.: gem list -i compass --version 0.12.
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 .
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With