@@ -179,6 +179,48 @@ def system(cmd, *args)
179179 _system ( cmd , *args )
180180 end
181181
182+ def install_gem_setup_path! ( name , version = nil , executable = name )
183+ # Respect user's preferences for where gems should be installed.
184+ ENV [ "GEM_HOME" ] = ENV [ "GEM_OLD_HOME" ] . to_s
185+ ENV [ "GEM_HOME" ] = Gem . user_dir if ENV [ "GEM_HOME" ] . empty?
186+ ENV [ "GEM_PATH" ] = ENV [ "GEM_OLD_PATH" ] unless ENV [ "GEM_OLD_PATH" ] . to_s . empty?
187+
188+ # Make rubygems notice env changes.
189+ Gem . clear_paths
190+ Gem ::Specification . reset
191+
192+ # Add Gem binary directory and (if missing) Ruby binary directory to PATH.
193+ path = PATH . new ( ENV [ "PATH" ] )
194+ path . prepend ( RUBY_BIN ) if which ( "ruby" ) != RUBY_PATH
195+ path . prepend ( Gem . bindir )
196+ ENV [ "PATH" ] = path
197+
198+ if Gem ::Specification . find_all_by_name ( name , version ) . empty?
199+ ohai "Installing or updating '#{ name } ' gem"
200+ install_args = %W[ --no-ri --no-rdoc #{ name } ]
201+ install_args << "--version" << version if version
202+
203+ # Do `gem install [...]` without having to spawn a separate process or
204+ # having to find the right `gem` binary for the running Ruby interpreter.
205+ require "rubygems/commands/install_command"
206+ install_cmd = Gem ::Commands ::InstallCommand . new
207+ install_cmd . handle_options ( install_args )
208+ exit_code = 1 # Should not matter as `install_cmd.execute` always throws.
209+ begin
210+ install_cmd . execute
211+ rescue Gem ::SystemExitException => e
212+ exit_code = e . exit_code
213+ end
214+ odie "Failed to install/update the '#{ name } ' gem." if exit_code . nonzero?
215+ end
216+
217+ return if which ( executable )
218+ odie <<-EOS . undent
219+ The '#{ name } ' gem is installed but couldn't find '#{ executable } ' in the PATH:
220+ #{ ENV [ "PATH" ] }
221+ EOS
222+ end
223+
182224 def run_bundler_if_needed!
183225 return unless Pathname . glob ( "#{ HOMEBREW_GEM_HOME } /bin/*" ) . empty?
184226
0 commit comments