ruk·si

Ruby
Using Local Gems

Updated at 2015-08-08 17:46

When you are creating your own gems to share features between Rails projects but want to keep them private, you can create a custom gem loader method in the Gemfile. Also useful for gem development.

def own_gem(name, *args)
  # See: https://github.com/bundler/bundler/blob/master/lib/bundler/dsl.rb#L74
  options = args.last.is_a?(Hash) ? args.pop.dup : {}
  version = args || [">= 0"]
  if ENV["USE_LOCAL_OWN_GEMS"]
    gem name, version, options.merge(:path => "../#{name}")
  else
    # You can get auth token from GitHub or by command line.
    # curl --verbose "https://api.github.com/authorizations" \
    #     -X POST \
    #     -H "Authorization: Basic $(echo -n 'username:password' | base64)" \
    #     -d '{"scopes":["repo_here"]}'
    gem name, version, options.merge(
        :git => "https://<TOKEN>:x-oauth-basic@github.com/<USER>/#{name}.git"
    )
  end
end

own_gem 'my_gem', '~> 0.0.5'
own_gem 'other_gem'

Gemfile.lock will have the commit hash if you update the gem without increasing the version in Gemfile.

GIT
  remote: https://<TOKEN>:x-oauth-basic@github.com/<USER>/<REPO>.git
  revision: <COMMIT_SHA>
  specs:
    my_gem (0.0.5)