Search code examples
rubypathrubygemsbundler

Bundler config to either look for gems in custom path or download from custom source


How do I configure bundler so that when I run bundle install it looks for gems under /my/custom/path first and if it doesn't find there then try to fetch them from a ruby gem remote repository hosted under https://a.nice.host and downloads those into ./local/relative/path (relative to cwd for example). I would like to avoid the bundler looking at default gem installation system path or rubygems.org


Solution

  • The syntax for sourcing a gem from a local folder is:

    gem 'some-gem-name', path: '/my/custom/path'
    

    And the syntax for specifying a custom source is:

    gem 'another-gem-name', source: 'https://a.nice.host'
    

    And to install gems into a specific local folder, you can run:

    bundle install --path ./local/relative/path
    

    Now, that's probably all the tools you need, in truth... (And in fact, especially for that last requirement, you may instead wish to look into rvm gemsets, or using bundle install --deployment.)

    But you did also ask about "looking in a local folder first, and only falling back to a remote source if it doesn't exist". That's quite an odd requirement (usually you'd only want to explicitly opt-in to fetching gems from a local path?!), but to answer this question as you've asked it...

    A Gemfile is literally just ruby code! So you can define this logic using... You guessed it, ruby! For example:

    if File.exists?('/my/custom/path')
      gem 'some-gem-name', path: '/my/custom/path'
    else
      gem 'some-gem-name', source: 'https://a.nice.host'
    end
    

    If this (unusual) pattern needs to be repeated in multiple places, you could wrap it into some helper method.

    For more information on the configuration options of bundler, please see the documentation.