Are you looking for a way to install PhantomJS automatically on program start? This ProTip is for you.

Consider the following program titles.rb. The example prints the titles of posts that appear in the main page of this blog.

The example works fine when command phantomjs is in $PATH. Otherwise you get this ugly error. In this case, try the following program magic-titles.rb. Line MAGIC installs PhantomJS in ~/phantomjs, so you might want to remove that directory afterwards. Now you get titles. The elided part consists of a list files that are installed in ~/.phantomjs. # How does MAGIC work? Line MAGIC installs PhantomJS and tells Poltergeist where to find command phantomjs. Installation happens when MAGIC calls method Phantomjs.path. The code that does the installation is located in method Phantomjs::Platform#install!. The code installs PhantomJS in ~/.phantomjs when PhantomJS is not installed there and is not in your $PATH.

MAGIC tells Poltergeist the path of command phantomjs by setting option page.driver.options[:phantomjs] to the path given by Phantomjs.path. The option is applied when visit 'http://ruslanledesma.com' executes. The code that applies the option is located in Poltergeist.

# Do’s and don’ts

Do apply this ProTip when you are doing a one-off task. Do remember to remove directory ~/phantomjs when you don’t need it anymore.

Do not apply this ProTip when installing PhantomJS by other means gives a shorter development cycle. For example, when you run you tests in a Docker container, install PhantomJS and either do not discard the container’s data or create a new image from the last state of the container. This way you will not lose time installing PhantomJS every time you run tests.

Do not apply this ProTip when there is a dedicated mechanism for installing dependencies. For example, when you need PhantomJS for a project and that project has a Gemfile, indicate that PhantomJS should be installed when dependencies for your project are installed.