Using bundlerEnv with non-default version of Ruby (v2.5)

I’m not an expert, but I think there is a simpler solution based off the nixpkgs manual here: https://github.com/NixOS/nixpkgs/blob/1f49035aca52303abb2e09976baf36f297eb68a6/doc/languages-frameworks/ruby.section.md

I first created a new directory with the following files:

# ./Gemfile
source "https://rubygems.org" do
  gem 'clockwork'
end

ruby '2.5.8'
# ./shell.nix
with (import <nixpkgs> {});
let
  gems = bundlerEnv {
    name = "example-for-floehopper";

    ruby = ruby_2_5;
    gemdir = ./.;
  };
in mkShell { buildInputs = [ gems gems.wrappedRuby ]; }
# ./bundler-shell.nix
with (import <nixpkgs> {});
let
  myBundler = bundler.override { ruby = ruby_2_5; };
in
mkShell {
  name = "bundler-shell";
  buildInputs = [ myBundler ];
}

Then I ran $ nix-shell --run “bundle lock” ./bundler-shell.nix to create the initial Gemfile.lock. If I try to use my system ruby or bundix -l to create the lockfile bundler raises an exception that my ruby version is wrong. After this step ./bundler-shell.nix isn’t needed though, as the shell provided by shell.nix will provide the correct ruby and bundler as soon as we create a gemset.nix.

Now that I have a Gemfile and Gemfile.lock I created the gemset.nix that bundlerEnv wants by running $ nix-shell --run “bundix” -p bundix. I had to do this before I could enter the final nix-shell because the bundlerEnv needs a gemset.nix file before it can be used.

Now if I enter the nix-shell I get the following

[nix-shell:~/ruby-test]$ which bundle
/nix/store/dra4g2dzacwadq9ymh72z0jlhzyd6y65-example-for-floehopper/bin/bundle

[nix-shell:~/ruby-test]$ cat `which bundle` | grep GEM_HOME
Gem.paths = { 'GEM_HOME' => "/nix/store/dra4g2dzacwadq9ymh72z0jlhzyd6y65-example-for-floehopper/lib/ruby/gems/2.5.0" }

[nix-shell:~/ruby-test]$ cat `which bundle` | grep LOAD_PATH
$LOAD_PATH.unshift "/nix/store/kf9zaq46m1w8ckmsrvsavhgg6jqlxncm-bundler-2.1.4/lib/ruby/gems/2.5.0/gems/bundler-2.1.4/lib"

I think this is the best way to go, but I’m not sure why the nixpkgs manual section I linked isn’t actually in the nixpkgs manual on the website.

1 Like