Gemfile
RubyGems is a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries (in a self-contained format called a "gem"), a tool designed to easily manage the installation of gems, and a server for distributing them.
Gemfile contains a list gems required by your project.
Let's start with creating a Gemfile for our project inside the working directory
~ ❯❯❯ cd ~/wad/hello
~/w/hello ❯❯❯ touch Gemfile
As our application does not have dependencies on any other gems except Sinatra, we need to add just one line to our Gemfile
source 'https://rubygems.org'
gem 'sinatra'
We now create our application file, let's name it app.rb
require 'sinatra'
get '/' do
'Hello world!'
end
These 4 lines are all that we need to build a hello world application. We can run this app.rb file as any other ruby code ruby app.rb
~/w/hello ❯❯❯ ruby app.rb
/Users/karim/.rvm/rubies/ruby-2.4.0/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- sinatra (LoadError)
from /Users/karim/.rvm/rubies/ruby-2.4.0/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from app.rb:1:in `<main>'
The error here says cannot load such file -- sinatra (LoadError) which means that it is looking for sinatra gem which we required in our application but could not find it locally. Let's go ahead and install it.
~/w/hello ❯❯❯ bundle install ⏎
Fetching gem metadata from https://rubygems.org/..........
Fetching version metadata from https://rubygems.org/.
Resolving dependencies...
Using rack 1.6.5
Installing tilt 2.0.7
Using bundler 1.14.3
Using rack-protection 1.5.3
Installing sinatra 1.4.8
Bundle complete! 1 Gemfile dependency, 5 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.
Try running the application again
~/w/hello ❯❯❯ ruby app.rb
[2017-03-31 02:45:58] INFO WEBrick 1.3.1
[2017-03-31 02:45:58] INFO ruby 2.4.0 (2016-12-24) [x86_64-darwin15]
== Sinatra (v1.4.8) has taken the stage on 4567 for development with backup from WEBrick
[2017-03-31 02:45:58] INFO WEBrick::HTTPServer#start: pid=85524 port=4567
This time it ran successfully and you can verify this by visiting http://localhost:4567/ on your browser.