Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby gems in stand-alone ruby scripts

This is a really basic ruby gems question. I'm familiar with writing simple ruby scripts like this:

#!/usr/bin/ruby
require 'time'
t = Time.at(123)
puts t

Now I'd like to use my own ruby gem in my script. In my rails project I can simply require 'my_gem'. However this doesn't work in a stand-alone script. What's the best/proper way to use my own gem in a stand-alone ruby script?

like image 755
SundayMonday Avatar asked Feb 11 '12 00:02

SundayMonday


People also ask

Does Jekyll use Ruby?

Jekyll is written in Ruby.


3 Answers

You should be able to simply require it directly in recent versions of Ruby.

# optional, also allows you to specify version
gem 'chronic', '~>0.6'

# just require and use it
require 'chronic'
puts Chronic::VERSION  # yields "0.6.7" for me

If you are still on Ruby 1.8 (which does not require RubyGems by default), you will have to explicitly put this line above your attempt to load the gem:

require 'rubygems'

Alternatively, you can invoke the Ruby interpreter with the flag -rubygems which will have the same effect.

See also:

  • http://docs.rubygems.org/read/chapter/3#page70
  • http://docs.rubygems.org/read/chapter/4
like image 169
Jeremy Roman Avatar answered Sep 28 '22 16:09

Jeremy Roman


You could use something like this. It will install the gem if it's not already installed:

def load_gem(name, version=nil)
  # needed if your ruby version is less than 1.9
  require 'rubygems'

  begin
    gem name, version
  rescue LoadError
    version = "--version '#{version}'" unless version.nil?
    system("gem install #{name} #{version}")
    Gem.clear_paths
    retry
  end

  require name
end

load_gem 'your_gem'
like image 38
Robert Kajic Avatar answered Sep 28 '22 17:09

Robert Kajic


It is to be noted that bundler itself can deal with this. It's particularly interesting since bundler ships with Ruby by default since version 2.6, and you don't need to install it manually anymore.

The idea is:

  1. to require bundler/inline at the top of your script,
  2. to use the gemfile method, and declare the gems you need inside a block, like you'd do in a Gemfile,
  3. after the end of this section, your gems are available!

For instance:

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'
  gem 'rainbow'
end

# From here on, rainbow is available so I can 
# print colored text into my terminal

require 'rainbow'
puts Rainbow('This will be printed in red').red

The official documentation can be found on bundler website: bundler in a single file ruby script

like image 35
Pierre-Adrien Avatar answered Sep 28 '22 15:09

Pierre-Adrien