Using Heroku you can privately host your gems in just a couple of minutes. Here’s how.
Start by creating an empty project folder, and add a Gemfile with only the source and ruby version:
1 # File: Gemfile 2 source 'https://rubygems.org' 3 ruby '2.0.0'
bundle to generate
Next, create a Procfile with the following content:
1 # File: Procfile 2 web: gem server -p $PORT
Then set up Git:
1 $ git init . 2 $ git add . 3 $ git commit -m Initial commit
Create a new Heroku app and push your application to Heroku:
1 $ heroku create 2 $ git push heroku master
Then launch your new privately hosted gem server in the browser:
1 $ heroku open
And just like that you have your very own private gem server. Now let’s push a gem to the server.
First you’ll want to create a .gitignore file and add .bundle to it so we don’t end up pushing our local Bundler settings to heroku:
1 $ echo ".bundle" >> .gitignore 2 $ git add .gitignore 3 $ git commit -m Ignoring the .bundle path
Next you’ll need a
vendor/cache folder. This is where you’ll place your
.gem files. So go ahead and create that folder now, and copy your
gem file into it.
1 $ mkdir vendor 2 $ mkdir vendor/cache 3 $ cp my.gem vendor/cache # replace 'my.gem' with your actual gem file
This is where things can get a little tricky. In order for us to push our gem
to Heroku, we need to first run
bundle install. However since our gem is
going to be privately hosted, Bundler will try and fail to download it from
rubygems.org. So we need to cache the gem first so it doesn’t try to download
it. Ironically, the way we do that is by using the
--no-cache flag. Then
you’ll need to run
bundle package --all to vendor your gem’s dependencies
along with the gem:
1 $ bundle install --no-cache 2 $ bundle package --all
bundle --no-cache tells Bundler that the
.gem files have already been
copied into the
vendor/cache folder, and it will install those instead of
connecting to rubygems.org.
bundle package --all downloads the missing
dependencies and copies their
.gem files into the
vendor/cache folder, thus
completing the installation.
It’s a bit confusing, but in the end it’s really only this three step process:
- Copy your private gem’s
bundle install --no-cache
bundle package --all
Then of course you’ll need to push those files to Heroku:
1 $ git add . 2 $ git commit -m Installed my private gem 3 $ git push heroku master
Refresh your browser, and you’ll notice that your gem will now be listed.
Now all you have to do to install the private gem in your application is add the URL to your Heroku app that’s hosting the gems to your Gemfile. For example:
1 # File myapp/Gemfile 2 source 'https://rubygems.org' 3 source 'http://private-gem-server.herokuapp.com' 4 5 gem 'my_private_app'