Setting Up a Rails Environment on OS X Mavericks

The easiest way to setup a Rails development environment is with RVM. It allows you to have multiple versions of Ruby and a different set of gems for each version on the same machine. With RVM you have the ability to run Ruby 1.9 for some of your projects and Ruby 2.1 for other, by simply switching versions.

Installing RVM

I will give you a short guide to installing RVM that always works for me. If something doesn’t work for you, there is a longer guide.

If you have RVM, you can just update it like this:

In the terminal:

rvm -v
# rvm 1.25.15 (stable) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]
rvm get stable

Prerequisites:

Here’s how you can check that you have all the requirements for installing RVM. All of these are included with OS X Mavericks as far as I can tell, but here’s how you can check.

In the terminal:

bash --version  # version should be 3.1.25 or higher
# GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
# Copyright (C) 2007 Free Software Foundation, Inc.
awk --version
# awk version 20070501
grep --version
# grep (BSD grep) 2.5.1-FreeBSD
which sed  # checking if you have which and sed
# /usr/bin/sed
curl --version
# curl 7.30.0 (x86_64-apple-darwin13.0) libcurl/7.30.0 SecureTransport zlib/1.2.5
# Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp 
# Features: AsynchDNS GSS-Negotiate IPv6 Largefile NTLM NTLM_WB SSL libz 
tar --version
# bsdtar 2.8.3 - libarchive 2.8.3
gunzip --version
# Apple gzip 2
bunzip2 --version
# bzip2, a block-sorting file compressor.  Version 1.0.6, 6-Sept-2010.

Fixing Dependencies

If you are missing one of the dependencies above, you can install them using Homebrew. Run a quick brew --version and if you don’t have it on your computer, here’s the short guide to installing it:

In the terminal

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

Great, now you can install the missing dependencies using the brew install command. It’s a great installer to have on your mac especially if you’re coming from the Linux world.

Installing curl with Homebrew:

brew install curl

We’re ready, let’s install RVM

In the terminal:

\curl -sSL https://get.rvm.io | bash -s stable

This will install Ruby Version Manager and RubyGems your machine. Once this is done you can check by running rvm -v in your terminal.

Installing Ruby

To install Ruby with RVM let’s look at a few commands. To see the versions of rails currently installed use the list command line argument.

In the terminal:

rvm list

To install a version of Ruby on the system let’s have a look at what’s available. Here’s a command that will list the versions of Ruby currently supported by your version of RVM.

In the terminal:

rvm list known

We’re interested in the MRI versions of Ruby, and the latest at this writing is Ruby 2.1.0 which came out a few weeks ago on Christmas day. Let’s install two versions of Ruby so we can switch between them. I will install Ruby 1.9.3 and Ruby 2.1.0.

Installing Ruby 1.9.3, in the terminal:

rvm install 1.9.3

Installing Ruby 2.1.0, in the terminal:

rvm install 2.1.0

If RVM complains about missing the compiler and ‘make’ tool, you should install Xcode and Command Line Tools. You can find Xcode on the Mac App Store. After you have installed it you might need to run it once so you can agree to the license before installing your rubies.

Switching Rubies

To switch between different versions of Ruby run the rvm use command. Try running something like this:

In the terminal:

rvm use 1.9.3
# Using /Users/codelittle/.rvm/gems/ruby-1.9.3-p484
ruby -v
# ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-darwin13.0.0]
rvm use 2.1.0
# Using /Users/codelittle/.rvm/gems/ruby-2.1.0
rvm -v
# ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin12.0]

Setting a default Ruby version

You can run multiple versions of Ruby, but one of them will be the default one. To specify your default Ruby version use the following command:

In the terminal:

rvm --default use 2.1.0

Project Specific Rubies

There is also a way to have project specific versions of Ruby. This is useful if you’re planning on running Pow with multiple gemsets on your machine.

Here’s the easiest way I found that works for me. Go to your project root path in the terminal and create a .ruby-version file, and simply write the version of Ruby inside it. Here’s a simple way to do it in the terminal.

In the terminal:

cd /path/to/project
echo "1.9.3" > .ruby-version
cd ./
# .ruby-version is seen by RVM on change dir
ruby -v
# ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-darwin13.0.0]

Installing Rails

Let’s switch to 2.1.0 and install Rails for this version. By now you’re likely to guess exactly how to do this.

In the terminal:

rvm use 2.1.0
gem install rails
### now wait some....

Generating our project

To test our rails installation let’s create an empty project using rails and call it ideapitch.

In the terminal:

rails new ideapitch -T

I hope this works for you. If you find difficulties setting things up, let me know in the comments below.

IdeaPitch Part I – Initial Thoughts

We’re beginning a new series on Rails development and will be building a small web application and callĀ it IdeaPitch. The idea of the app is simple, it will allow you to post your idea and let other people vote on it and give you feedback.

Wireframe & mockups

I like to begin by creating a wireframe or two of the pages our users will spend most of their time on. I begin with gray boxes and text, because it’s faster. Gradually I add colors, detail and icons to get things to look a little better.

Main page, latest idea pitches:

IdeaPitch, Basic Wireframe

Main page with more detail:

IdeaPitch, Adding Detail

Single idea page, allows you to vote and critique:

Single Idea Pitch with Comments and Critique

I hope you will join me as I build this app. I haven’t written this app yet, so I expect to change course often during this series, but hopefully this will only add to the learning experience.

If you have any ideas or questions, I look forward to hearing about them in the comments.

Simple Models With Sequel in Sinatra, Part V

This is the last article in the Simple Models with Sequel in Sinatra series. I thought that it would be nice to apply some of the things we learned in previous posts about code blocks.

The code in this post is meant to show a quick and dirty way to sort our entries in our simple phonebook application to make it more phonebook-like. There are cleaner ways to do it, but this will do for our example.

The route

We will do most of our processing in our route. We want to group all the contacts by the first letter of the first name, and pass them to our views for rendering.

Let’s begin by sorting our contacts by first name. To do this let’s use the .order method on the class. Then let’s use the .map and .each methods to get the first letters of the entries, and store the object values of each contact that starts with that letter in an array.

It may sound complicated, but if you go over the code a few times you will get an idea for what it does exactly. In the end everything gets stored inside @collections.

In app.rb:

get '/' do
  @page_title = "Contacts"
  @page_description = "Phonebook Application Example"
  @contacts = Contact.order(:first_name)
  @collections = {}
  letters = @contacts.map { |contact| contact.first_name.chars.first.capitalize }.uniq
  letters.each do |letter|
    @collections[letter.to_sym] = @contacts.map do |contact|
      contact if contact.first_name.chars.first.capitalize == letter
    end.compact!
  end
  erb :contacts
end

I have used a bunch of functions which you can learn more about by visiting Ruby Documentation. Here’s a list:

The view

Once the sorting and grouping of our contacts is done, let’s unpack our @collections array and iterate through it to render our contacts. In your views/contacts.erb replace everything in between the #contacts div with the markup below.

In views/contacts.erb

<div id="contacts" class="row">

	<% if @collections.empty? %>
		<div class="empty-phonebook columns-12">
			No entries in the phonebook
		</div><!-- end empty-phonebook -->
	<% else %>
    
	    <% @collections.each do |collection| %>

	      <div class="columns-12">
	        <h1 class="letter">
				<%= collection.first %>
			</h1>
			
	        <div class="row">
	        <% collection.last.each do |contact| %>
			
	          <div class="columns-4">
	            <div class="contact">
	              <h1>
					  <%= "#{contact.first_name} #{contact.last_name}"%>
				  </h1>
	              <p>
	                <strong>Phone:</strong>
	                <%= contact.phone_number %>
	              </p>
	              <p>
	                <strong>Email:</strong>
	                <%= contact.email_address %>
	              </p>
	              <p>
	                <strong>Address:</strong>
	                <%= contact.full_address %>
	              </p>
	              <% if !contact.notes.empty? %>
	              <p>
	                <strong>Notes:</strong>
	                <%= contact.notes %>
	              </p>
	              <% end%>
				  
	              <div class="actions">
	                <a class="button" href="/edit/<%= contact.id %>">Edit</a>
	                <a class="button" href="/delete/<%= contact.id %>">Delete</a>
	              </div>
				  
	            </div><!-- end  .contact -->
	          </div><!-- end .columns-4 -->
			  
	        <% end %>
	      </div><!-- row -->
		  
		</div><!-- end columns-12 -->

	    <% end %>

  <% end # endifelse %>
  
</div><!-- end #contacts .row -->

If you run your Sinatra application now, it should display the contacts neatly sorted and grouped by their starting letter.

The icing on the cake

Just because we can, let’s add a few more lines to our public/css/main.css to make this example look more like a phonebook. Paste the first line of CSS to the top of the file, and the rest of it after all the styles we wrote in our last posts.

In the top of public/css/main.css:

@import url(http://fonts.googleapis.com/css?family=Exo+2:300,700,500);

Towards the bottom of public/css/main.css:

/* Go a little crazy */

body {
	font-family: 'Exo 2', sans-serif;
	color: #333;
	
	/* Texture */
	background-color: #fafef0; 
	background-image: 
	linear-gradient(90deg, transparent 79px, #abced4 79px, #abced4 81px, transparent 81px),
	linear-gradient(#eee .1em, transparent .1em);
	background-size: 100% 1.2em;
}

.contact {
	border: 1px dashed #abcfd5;

	/* Texture */
	background-color: #fff; 
	background-image: 
	linear-gradient(#eee .1em, transparent .1em);
	background-size: 100% 1.2em;
	
	/* Box shadow */
	-webkit-box-shadow: 3px 2px 10px 0px rgba(0, 0, 0, 0.2);
	-moz-box-shadow:    3px 2px 10px 0px rgba(0, 0, 0, 0.2);
	box-shadow:         3px 2px 10px 0px rgba(0, 0, 0, 0.2);
}

What it should looks like

Phone book preview

We’re done

I enjoy sharing my experience with Sinatra. It is a small but delightful framework worth studying and using. I’d like to remind you that you can use the comments to ask questions.

Review the entire source code on GitHub.

This series is over, see you in a different one.

Simple Models With Sequel in Sinatra, Part IV

Simple Validations with Sequel Models in Sinatra

This is the third post in the series Simple Models With Sequel in Sinatra.

When you write an application it’s important to detect errors and associate them with error messages when saving or updating models. This way you can ensure the integrity of the data you are collecting from the users. In this post we will explore model validations with Sequel.

Client Side Validations

You can validate forms using javascript in the browser as he fills out the different fields. The nice thing about validating in the browser is that the response is immediate and it usually leads to better user experience. For example if you enter an invalid email address in a field and move to the next one, the error message appears immediately.

We’ll leave this type of form validation for a different post.

Server Side Validations

Doing validations on the server side is safer. But the user experience isn’t the best. You basically fill out the form and click on the submit button (e.g. “Save Contact”). The data from the form is then sent to the server through a put request for validation. If there are errors, they are shown on the next reload through some sort of notifications, like our flash messages.

The solution is to do both, client side for the usability and server-side validation for data integrity.

To better understand how things work we will begin backwards with server side validations, using Sequel’s built in validation_helpers plugin.

# Validating Models with Sequel

To validate a model we will have to add some code to our models inside models.rb. Pay special attention to the highlighted lines.

In models.rb:

require "rubygems"
require 'sequel'

Sequel::Model.plugin(:schema)
DB = Sequel.sqlite('database.db')

unless DB.table_exists? (:contacts)
  DB.create_table :contacts do
    primary_key :id
    string      :first_name, :null => false
    string      :last_name
    string      :phone_number
    string      :email_address
    text        :full_address
    text        :notes
    string      :avatar_file
    timestamp   :created_at
    timestamp   :updated_at
  end
end

class Contact < Sequel::Model(:contacts)
  # Contact Model
  plugin :validation_helpers

  def validate
    super
    validates_presence [:first_name, :email_address]
    validates_format /^.+@.+$/, :email_address, :allow_blank=>true
  end

end

On line ten we are setting a database rule that simply says first_name can’t be blank. On line twenty-four we ask the model to include Sequel’s validation framework.

Next on line twenty six we modify a class method called validate which I suspect gets called by the .valid? method. In following lines we provide validations. One is for presence and the next one is for format. There’s a list of validations you can run on your object attributes, and you can read it here: Sequel Validations.

Have a look at the line that says:

validates_format /^.+@.+$/, :email_address, :allow_blank=>true

Here we validate the email_addresss against a regular expression. Do not use this validation for anything important but find a more comprehensive one. To learn more about regular expressions pattern matching you can google it, or skim over this article.

Modifying inside our routes

There are a few modifications we’ll make inside our routes. For instance, we will not attempt to @contact.save a model, but instead we will run a @contact.valid?.

In your app.rb

get '/new' do
  @page_title = "New Entry"
  @page_description = "Add a new entry to your the phonebook"
  @contact = Contact.new
  erb :new
end

post '/create' do
  @contact = Contact.new
  @contact.set_fields(params[:contact], [:first_name, :last_name, :phone_number, :email_address, :full_address, :notes])
  @contact.created_at = Time.now.to_s
  if @contact.valid?
    @contact.save # all good, let's save the model
    flash[:notice] = "Awesome, the new entry has been added successfully."
    redirect "/"
  else
    @page_title = "New Entry"
    @page_description = "Please try to enter the data again"
    flash.now[:error] = "I tried, but something went wrong."
    erb :new
  end
end

get '/edit/:id' do
  @page_title = "Edit Entry"
  @page_description = "Edit an existing entry"
  @contact = Contact[params[:id].to_i]
  erb :edit
end

post '/update/:id' do
  @contact = Contact[params[:id].to_i]
  @contact.set_fields(params[:contact], [:first_name, :last_name, :phone_number, :email_address, :full_address, :notes])
  @contact.updated_at = Time.now.to_s
  if @contact.valid?
    @contact.save
    flash[:notice] = "The entry has been updated successfully." 
    redirect "/"
  else
    @page_title = "Edit Entry"
    @page_description = "Edit an existing entry"
    flash.now[:error] = "I tried hard, but something went wrong."
    erb :edit
  end
end

When there’s an error, two things will happen when you run .valid? on the model. First, this method will of course return false. And second, the validation errors collect inside @contact.errors.

Note that for flashes I am using flash.now[:error] and instead of doing a redirect like before, I am rendering the :new and :erb views directly in the put route. The reason I’m doing this is so our @contact instance variable doesn’t reset to a new instance of the model, so we can keep the text inside the input boxes and so the user doesn’t have to type the whole thing again. If this doesn’t make sense, let me know in the comments.

Besides, I’m not sure this is the accepted way of doing this. Most likely it isn’t, but it seems to work for this example.

Displaying validation errors

To display the errors let’s check if there are any and output them. And we will do this inside our _form.erb partial to keep these errors separate from the flash notices we created in our last post. I want to keep the errors closer to the form, and also I don’t want them to disappear in 5 seconds like our flash messages currently do.

So let’s add this to the top of the file, before everything else.

In _form.erb:

<% if !@contact.errors.empty? %>
<div class="row">
  <div class="columns-12">
    <div id="form-errors">
      <% @contact.errors.full_messages.each do |msg| %>
      <div class="error">
        <%= @contact.pretty_names(msg) %>
      </div>
      <% end %>
    </div>
  </div>
</div>
<% end %>

And let’s go ahead and style our newly created styles for form errors.

Somewhere inside public/css/main.css

/* Form Errors */

#form-errors {
  border: 1px solid #eee;
  background: #fafafa;
  padding: 10px;
}

#form-errors .error {
  font-size: 14px;
  font-weight: bold;
  display: block;
  padding: 2px 0;
  color: #821515;
}

I think this is all for this post. In case I missed something in the post have a look at the full source code below.

Download Source Code: Simple Sinatra Models with Sequel Validations

Simple Models With Sequel in Sinatra, Part III

This is the third post in the series Simple Models With Sequel in Sinatra.

In this post we will add an important interface element we will need for validations later, the flash notices.

Displaying Flash Notices

We want to have a way to display a message to the user about the success or failure of his actions. For example, when you create a new entry we’ll give our app the ability to flash a message that it has been successfully created, or there was an error.

Flash notices:

Flash Notice in Sinatra

Sinatra doesn’t provide this feature by default so we have to use a third-party solution. I chose to use a gem called sinatra-flash.

Here’s a simple way to install it with RubyGems:

In the terminal

gem install sinatra-flash

Now let’s require it in our app.rb, and for this gem to work we must enable Sinatra’s built in support for sessions. The first six line in your file should look like this:

In app.rb

require 'rubygems'
require 'sinatra'
require 'sinatra/flash'
require_relative 'models'

enable :sessions

# the rest of the code

To display a notice we use the following construction:

flash[:type] = "Notice message goes here"
redirect '/route'

The :type can be anything like :notice, :error, :warning, :insert_color_name_here and these symbols will be added as a class to our .flash div element. The flash message will only show on the next request, which in our case is a redirect.

Let’s modify our code to add flash messages to our redirects in app.rb. Please note that the /delete route has modified slightly.

In app.rb

post '/create' do
  @contact = Contact.new
  @contact.set_fields(params[:contact], [:first_name, :last_name, :phone_number, :email_address, :full_address, :notes])
  @contact.created_at = Time.now.to_s
  if @contact.save
    flash[:notice] = "Awesome, the new entry has been added successfully."
    redirect "/"
  else
    flash[:error] = "I tried hard, but something went wrong."
    redirect "/new"
  end
end

post '/update/:id' do
  @contact = Contact[params[:id].to_i]
  @contact.update_fields(params[:contact], [:first_name, :last_name, :phone_number, :email_address, :full_address, :notes])
  @contact.updated_at = Time.now.to_s
  if @contact.save
    flash[:notice] = "The entry has been updated successfully." 
    redirect "/"
  else
    flash[:error] = "I tried hard, but something went wrong."
    redirect "/edit/#{@contact.id}"
  end
end

get '/delete/:id' do
  # a get request delete route
  @contact = Contact[params[:id].to_i]
  if @contact.delete
    flash[:notice] = "All good, entry deleted."
    redirect '/'
  else
    flash[:error] = "I tried hard, buy couldn't delete the entry."
    redirect '/'
  end
end

For the errors to display we must add them to our layout.erb template. Sinatra-flash provides us with a handy method called styled_flash that wraps our messages in div elements with classes. Let’s place it right before the yield statement.

In views/layout.erb:

<!-- Add your site or application content here -->
		<div class="row">
			<div class="columns-12">
				<%= styled_flash %>
				<%= yield %>
			</div>
		</div>

Lastly we want to style the divs with CSS, and while we’re at it some simple javascript to hide the messages in 5 seconds after they are displayed.

In public/css/main.css:

/* Flash notices */

#flash {
  margin-bottom: 20px;
}

#flash .flash {
  font-size: 14px;
  font-weight: bold;
  display: block;
  padding: 5px 10px;
  background-color: #d8eaef;
}

#flash .flash.notice {
  background-color: #ffd35e;
}

#flash .flash.error {
  color: #821515;
  background-color: #ffacac;
}

This is optional, in public/js/main.js:

$(document).ready(function() {
  if ($("#flash").length > 0) {
    // Hide the flash in a few seconds
    setTimeout(function() {
      $("#flash").remove()
    }, 5000)
  }
});

Start your Sinatra app and go create a few entries, and delete some. Study the code to figure out how this works. I hope that this was useful.

Simple Models With Sequel in Sinatra, Part II

Let’s pick up where we left off in the previous post. We now have our persistent model and a way to display it on our main route. In this post we will provide a way to create, update and delete a phonebook entry.

Let’s start by adding a /new route to our app.rb.

In app.rb:

get '/new' do
  @page_title = "New Entry"
  @page_description = "Add a new entry to your the phonebook"
  @contact = Contact.new
  erb :new
end

Sinatra will look for new.erb inside the project’s views directory. But rather than creating this file, let’s create our form in a separate file and pull it into new.erb afterwards. This type of templates are called partials, and we will call ours _form.erb. Sinatra doesn’t require you to start the names of partials with underscore like Rails does, but it’s a good habit to have them look different visually.

The reason we want to extract the form into a partial is so we can reuse it later for the edit route.

In views/_form.erb

<div class="row">
  <form action="<%= route %>" method="<%= action %>" accept-charset="utf-8">
  <div class="columns-6">
    <label for="first_name">First Name:</label>
    <input type="text" name="contact[first_name]" 
        id="first_name" value="<%= @contact.first_name %>" />
  </div>
  <div class="columns-6">
    <label for="last_name">Last Name:</label>
    <input type="text" name="contact[last_name]" 
        id="last_name" value="<%= @contact.last_name %>" />
  </div>
  <div class="columns-6">
    <label for="phone_number">Phone Number:</label>
    <input type="text" name="contact[phone_number]" 
        id="phone_number" value="<%= @contact.phone_number %>" />
  </div>
  <div class="columns-6">
    <label for="email_address">Email Address:</label>
    <input type="text" name="contact[email_address]" 
        id="email_address" value="<%= @contact.email_address %>" />
  </div>
  <div class="columns-6">
    <label for="full_address">Full Address</label>
    <textarea name="contact[full_address]" 
         id="full_address" rows="4" cols="40"><%= @contact.full_address %></textarea>
  </div>
  <div class="columns-6">
    <label for="notes">Notes:</label>
    <textarea name="contact[notes]" 
        id="notes" rows="4" cols="40"><%= @contact.notes %></textarea>
  </div>
  <div class="columns-12">
    <button type="submit">Save Contact</button>
  </div>
</form>
</div>

And now let’s create our new.erb template and render our form partial inside the template using the same erb method we use in our routes.

But this time we will ask Ruby to pass along to our partial two local variables which are route and action. We want to pass these variables os later we can send a different action and route to this form on the edit page.

In new.erb

<a href="/" class="button large new">Back</a>

<h1><%= @page_title %></h1>
<p class="description"><%= @page_description %></p>

<!-- form partial -->
<%= erb :_form, locals: {action: "post", route: "/create"} %>

And let’s fix the styling in CSS to make our forms better. Add these styles to your public/css/main.css.

In main.css:

/* All the form styling we will need for now */

button[type=submit] {
  font-size: 18px;
  border: 2px solid #aaa;
  border-radius: 3px;
  padding: 8px 20px;
}

label,
input,
textarea {
  width: 100%;
  padding: 5px 0;
  line-height: 20px;
}

Now run ruby app.rb in your terminal and in your browser go to localhost:port_number/new to see your form.

In your browser:

New Action, Simple Sinatra and Seaquel

Saving the form data to the database

To save the form to the database we need to create a post request and point to the /create route. It will accept all the form data from new.erb and if possible will save it to the database. We won’t deal with validations and flash messages in this article.

Now let’s add this new route to your app.rb

In app.rb:

post '/create' do
  @contact = Contact.new
  @contact.set_fields(params[:contact], [:first_name, :last_name, :phone_number, :email_address, :full_address, :notes])
  @contact.created_at = Time.now.to_s
  if @contact.save
    redirect "/"
  else
    redirect "/new"
  end
end

If you look at line three, we use the method set_fields and pass params[:contact] to it. These are the form values we collect through _form.erb. And to protect from mass assignment the second argument tells the method exactly which fields it should allow by passing an array with values as its second argument.

This is all you need for now. Let’s add some validation and flash notices in a later post.

Editing Our Entries

Now that we can create new entries, let’s make a way to edit them. We will create an /edit route and an edit.erb. And will reuse the _form.erb for in the edit view. We also need an /update route where we can send our updated values to the model in the database.

In app.rb

get '/edit/:id' do
  @page_title = "Edit Entry"
  @page_description = "Edit an existing entry"
  @contact = Contact[params[:id].to_i]
  erb :edit
end

post '/update/:id' do
  @contact = Contact[params[:id].to_i]
  @contact.update_fields(params[:contact], [:first_name, :last_name, :phone_number, :email_address, :full_address, :notes])
  @contact.updated_at = Time.now.to_s
  if @contact.save
    redirect "/"
  else
    redirect "/edit/#{@contact.id}"
  end
end

In edit.erb

<a href="/" class="button large new">Back</a>

<h1><%= @page_title %></h1>
<p class="description"><%= @page_description %></p>

<!-- form partial -->
<%= erb :_form, locals: {action: "post", route: "/update/#{@contact.id}"} %>

Deleting An Entry

Lastly, let’s create a route that when accessed will simply delete an entry. If you go back to our previous post you’ll find that the delete button points to /delete/some_number. Let’s create a route, and ask Sequel to delete the entry from the database if it exists.

In app.rb

get '/delete/:id' do
  # a get request delete route
  @contact = Contact[params[:id].to_i]
  @contact.delete if !@contact.nil?
  redirect "/"
end

Now you know how to create, read, update and delete your persistent models with Sequel in Sinatra. Learning how things work in Sinatra also helps me understand Rails deeper and better. I hope you enjoyed the post.

Download Source Code: Simple Sinatra Models with Sequel

The Fastest Way to Configure Vim for Ruby Development on Your Mac

This is going to be a short post on an easy way to quickly configure your Vim for Ruby development. The post is primarily for the more seasoned Vim users, those who habitually type :w in all the wrong places. But even if you’re not, configuration is a good place to start.

I recently needed to quickly configure a Mac for Ruby development, and discovered this simple way that will get you very far very quickly. Here’s one of the best and cleanest Vim, Git and Shell configurations on Github, with two small tweaks of my own.

YADR

https://github.com/skwp/dotfiles

To install run this in your terminal:

sh -c "`curl -fsSL https://raw.github.com/skwp/dotfiles/master/install.sh`"

Have a look at the two screenshots below, you can achieve this by simply following the instructions on the GitHub page. Here’s the short version, all you have to do is run this command:

OS X Mavericks terminal, with Git prompt, autocompletes and more.

Solarize Theme

Vim, fully configured:

Vim with YADR

This configuration repo is quite “configurable”. To get the most out of it, read throughout the entire README.md on GitHub.

Solarized theme for the native OS X terminal

I like to add a lot of my own tweaks and shortcuts to my Vim config but I won’t be able to go over those in this post. But I will share how to make the most of these settings in the native OS X terminal.

Downloading and importing the Solarized color scheme

Setting up the theme is simple, download the terminal themes and import them inside your terminal settings.

Solarized Theme Files: tamul / solarized-osx-terminal-colors

Now open your terminal, and hit Ctrl+, to open the settings. In your settings pane find the themes and import them from the downloaded terminal colors. The themes are located inside the xterm-256color folder.

Terminal Settings

Do note, this config will disable the arrow keys in Vim, to increase your efficiency I guess. Instead use the j k h l keys.

That’s it for today, I hope this was useful.

Simple Models With Sequel in Sinatra, Part I

Today we’ll look at a simple persistent model using Sequel in Sinatra. Sequel is a lightweight super nice ORM for Ruby. It’s well maintained and growing in popularity.

What do you need on your machine?

If you don’t have Sequel on your computer, here’s how to install it:

In the terminal:

gem install sequel

Let’s get started

To begin, let’s use our Sinatra + HTML5 Boilerplate application template. I have since added little-grid, a CSS grid we created in an earlier post.

In the terminal:

cd ~/path/to/projects
git clone --depth=1 https://github.com/codelittle/sinatra-h5bp.git
Cloning into 'sinatra-h5bp'...
remote: Counting objects: 23, done.
remote: Compressing objects: 100% (19/19), done.
remote: Total 23 (delta 0), reused 20 (delta 0)
Unpacking objects: 100% (23/23), done.
Checking connectivity... done

# Let's rename our application folder
mv sinatra-h5bp simple-models-sinatra
cd simple-models-sinatra

Creating Our Model

To keep things as simple as possible for this tutorial we will build a model that stands alone and has no relationship to any other model. A simple phonebook application will suite our us perfectly, and we’ll call our model Contact.

Let’s get started

There are better ways to separate concerns in Sinatra, but for the sake of simplicity we will create a file in our application directory and call it models.rb and then use require_relative to load it in our application.

In the terminal:

cd ~/path/to/projects/simple-models-sinatra
touch models.rb

In app.rb

require 'rubygems'
require 'sinatra'
require_relative 'models'

Writing our models.rb

Now let’s open models.rb and make sure we require sequel. We will then tell Sequel to use sqlite3 and to store our database in the file database.db.

In the next lines we will check if our table for contacts exists, and if not we will tell Sequel how how to create it.

Lastly we will create our Model to go along with our database table. To do this we create a new class that extends Sequel::Model and supply the name of our table. And, we’re done here.

In models.rb

require "rubygems"
require 'sequel'

Sequel::Model.plugin(:schema)
DB = Sequel.sqlite('database.db')

unless DB.table_exists? (:contacts)
  DB.create_table :contacts do
    primary_key :id
    string      :first_name, :null => false
    string      :last_name
    string      :phone_number
    string      :email_address
    text        :full_address
    text        :notes
    string      :avatar_file
    timestamp   :created_at
    timestamp   :updated_at
  end
end

class Contact < Sequel::Model(:contacts)
  # Contact Model
end

This should look familiar if you’re experienced with frameworks that implement the Model View Controller design patterns such as Rails or Django.

Our database file

Let’s have a look at our database schema. To do this, in your terminal change directory to the project directory and run sqlite3 database.db.

In the terminal

sqlite3 database.db

This will run the sqlite3 command prompt. In the command prompt you can run commands like .schema to see the database schema, .tables to list the existing tables and .quit to exit the prompt.

Building the contacts listing page

Now that our Contact model exists, let’s edit our main route and view. In app.rb replace the main route with the following one:

In app.rb

get '/' do
  @page_title = "Contacts"
  @page_description = "Phonebook Application Example"
  @contacts = Contact.all
  erb :contacts
end

On line four the @contacts instance variable takes our model the all method. This is good for now.

Note also that the erb method points to a view that doesn’t exist, so let’s create it. In your views folder create a new file and call it contacts.erb. Then open the file in an editor and paste the following code:

In views/contacts.erb:

<a href="/new" class="button large new">New Entry</a>

<h1><%= @page_title %></h1>
<p class="description"><%= @page_description %></p>

<div id="contacts" class="row">
	<% if @contacts.empty? %>
	<div class="empty-phonebook columns-12">
		No entries in the phonebook
	</div>
	<% else %>
	
		<% @contacts.each do |contact| %>
		
		<div class="columns-4">
			<div class="contact">
				<h1><%= "#{contact.first_name} #{contact.last_name}"%></h1>
				<p>
					<strong>Phone:</strong>
					<%= contact.phone_number %>
				</p>
				<p>
					<strong>Email:</strong>
					<%= contact.email_address %>
				</p>
				<p>
					<strong>Address:</strong>
					<%= contact.full_address %>
				</p>
				<% if !contact.notes.empty? # let's show notes only if they exist %>
				<p>
					<strong>Notes:</strong>
					<%= contact.notes %>
				</p>
				<% end%>
				<div class="actions">
					<a class="button" href="/edit/<%= contact.id %>">Edit</a>
          		  	<a class="button" href="/delete/<%= contact.id %>">Delete</a>
				</div>
			</div>
		</div>
	
		<% end %>
	
	<% end %>
</div>

And let’s add some extra styles to get our contacts to look a little better.

In your public/css/main.css:

/* Custom Styles */

p.description {
	font-weight: 100;
	font-size: 24px;
}

.empty-phonebook {
	font-size: 48px;
	color: #aaa;
}

#contacts .columns-4:nth-child(3n+1) {
	clear:left;
	/* clears before each new row */
}

.contact {
	padding: 20px;
	border: 1px dashed #aaa;
}

.contact h1 {
	font-size: 24px;
	margin: 0 0 20px;
}

.contact p {
	margin: 10px 0;
}

.contact .actions {
	opacity: 0;
	padding: 5px 0 0;
}

.contact:hover .actions {
	opacity: 1;
}

a.button {
	font-size: 12px;
	font-weight: bold;
	cursor: pointer;
	border: 1px solid #aaa;
	border-radius: 3px;
	padding: 4px 10px;
	color: #333;
	text-decoration: none;
}

a.button.large,
button[type=submit] {
	font-size: 16px;
	padding: 8px 10px;
	margin: 28px 0;
	float: left;
	background: #eee;
	border: 1px solid #aaa;
    border-radius: 3px;
}

a.button.new {
	float: right;
}

Adding data to the table data

Now we want to add some sample entries to our database to make sure our model works and is persistent. We will build a few routes in a later tutorial, but for now let’s open an irb session and populate the database manually.

To start an interactive Ruby shell session go into your terminal, change directories to your project home and run the command: irb. Follow the next screen to add some sample entries to your database:

Inside IRB

load './app.rb'
=> true
Contact.create(first_name: "Tim", last_name: "Cook", phone_number: "1-800-MY-APPLE", email_address: "tim@apple.com", full_address: "1 Infinite Loop Cuppertino, CA 95014", notes: "CEO of Apple Inc.")
=> #<Contact @values={:id=>2, :first_name=>"Tim", :last_name=>"Cook", :phone_number= >"1-800-MY-APPLE", :email_address=>"tim@apple.com", :full_address=>"1 Infinite Loop Cuppertino, CA 95014", :notes=>"CEO of Apple Inc.", :avatar_file=>nil, :created_at=>nil, :updated_at=>nil}>
Contact.create(first_name: "John", last_name: "Smith", phone_number: "1-800-122-2355", email_address: "johnsmith@email.com", full_address: "Corner Street 11, CA 94040", notes: "Agent Smith from the Matrix")
=> #<Contact @values={:id=>4, :first_name=>"John", :last_name=>"Smith", :phone_number=>"1-800-122-2355", :email_address=>"johnsmith@email.com", :full_address=>"Corner Street 11, CA 94040", :notes=>"Agent Smith from the Matrix", :avatar_file=>nil, :created_at=>nil, :updated_at=>nil}> 
Contact.create(first_name: "Dave", last_name: "Johnson", phone_number: "1-800-123-4567", email_address: "djohnson@email.com", full_address: "East Street 20, CA 94040", notes: "I met Dave on a flight overseas, that's how I know him")
=> #<Contact @values={:id=>5, :first_name=>"Dave", :last_name=>"Johnson", :phone_number=>"1-800-123-4567", :email_address=>"djohnson@email.com", :full_address=>"East Street 20, CA 94040", :notes=>"I met Dave on a flight overseas, that's how I know him", :avatar_file=>nil, :created_at=>nil, :updated_at=>nil}>
Contact.create(first_name: "Joe", last_name: "Black", phone_number: "1-401-345-5678", email_address: "joeblack@email.com", notes: "Met him at a praty.")
=> #<Contact @values={:id=>6, :first_name=>"Joe", :last_name=>"Black", :phone_number=>"1-401-345-5678", :email_address=>"joeblack@email.com", :full_address=>nil, :notes=>"Met him at a praty.", :avatar_file=>nil, :created_at=>nil, :updated_at=>nil}> 

Done for now

Now let’s run the server and see what we’ve done so far.

In your terminal:

cd ~/path/to/projects/simple-sinatra-models
ruby app.rb
[2014-01-09 01:35:51] INFO  WEBrick 1.3.1
[2014-01-09 01:35:51] INFO  ruby 2.0.0 (2013-06-27) [x86_64-darwin12.4.0]
== Sinatra/1.4.4 has taken the stage on 4567 for development with backup from WEBrick
[2014-01-09 01:35:51] INFO  WEBrick::HTTPServer#start: pid=7166 port=4567

You should see something like this:

Safari Preview

I hope this was useful. I will be writing a part two to this article. In the next article we will add a few more routes such s new, edit and delete.

Let’s Learn Emmet for HTML

Emmet LogoEmmet is a delightful abbreviation system that adds fun and speed to writing HTML and CSS. It is more than worth learning and adopting into your workflow. In this article I will show you everything you need to know to get started with Emmet for HTML.

Install Emmet

To begin you will likely need to install the Emmet plugin for your code editor. It supports most of the popular ones including Sublime Text, TextMate, RubyMine and Vim.

Download Page

Let’s get started

On most editors Emmet will be triggered by typing an abbreviation and hitting the Tab key. If you’re using TextMate, you might have to go into Emmet > Emmet Preferences to get it to expand on Tab.

We’ll try with the most basic abbreviation for h1, make sure you press the tab key where you see the [tab] notation.

In your code editor

h1[tab]

Should expand to:

<h1></h1>

Emmet will expand any tag the same way. Can you guess what the next shortcut does?

In your code editor

hgroup>h1+h2[tab]

This abbreviation will expand to a parent hgroup tag, and two sibling h1 and h2 elements. The notations for child and sibling are borrowed from CSS child > and sibling + selectors.

Previous code should expand to:

<hgroup>
	<h1></h1>
	<h2></h2>
</hgroup>

Note also that the editor caret will position itself between the h1 tags, and you can use the Tab to move to the next position between the h2 tags.

Emmet Shorthands

Some of the longer tags have further abbreviations, here are a few of them:

  • blockquote can be invoked with bq
  • figure can be invoked with fig
  • figcaption can be invoked with figc
  • textarea can be invoked with tarea
  • caption can be invoked with cap
  • button can be invoked with btn
  • address can be invoked with adr

One of my favorite ones is the ! (exclamation mark) followed by tab abbreviation, because it expands to a minimal boilerplate HTML5 document to get you started, it looks like this:

Expanding ! does:

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>Document</title>
</head>
<body>
	
</body>
</html>

IDs and Classes

To create a div with an id and a few classes, just do this:

Id & class abbreviation:

#top.this.container[tab]

Expands to:

<div id="top" class="this container"></div>

If you need to expand something else than a div, then follow the tag you’d like to expand with the id and classes you’d like for it.

Try this:

header#main.container>div.row>div.four.columns+div.eight.columns[tab]

Should expand to this:

<header id="main" class="container">
	<div class="row">
		<div class="four columns"></div>
		<div class="eight columns"></div>
	</div>
</header>

Expanding multiple elements with automated numbering

If you need to expand multiple elements such as an unordered list, all you need to do is to multiply * the element by the number of items, in our case li*4. Another neat feature Emmet makes available the substitution of the $ symbol with the item number as it iterates. Let’s see it in action:

In your editor:

nav>ul>li*4>a.link-$[tab]

Should expand to:

<nav>
	<ul>
		<li><a href="" class="link-1"></a></li>
		<li><a href="" class="link-2"></a></li>
		<li><a href="" class="link-3"></a></li>
		<li><a href="" class="link-4"></a></li>
	</ul>
</nav>

On each iteration emmet substituted link-$ with the appropriate one. To get even more out of the automated numbering you can insert multiple $ symbols to further format the output of the numbers.

In your editor:

ul>li*3>a.list-$$[tab]

Should expand to:

<ul>
	<li><a href="" class="list-01"></a></li>
	<li><a href="" class="list-02"></a></li>
	<li><a href="" class="list-03"></a></li>
</ul>

Grouping items

Emmet also lets you group items together using parentheses. In the following example Emmet will expand the stuff inside the parentheses first, and add the div#menu-button separately.

In your editor:

nav>(ul>li*4>a.link-$)+div#menu-button[tab]

Should expand to:

<nav>
	<ul>
		<li><a href="" class="link-1"></a></li>
		<li><a href="" class="link-2"></a></li>
		<li><a href="" class="link-3"></a></li>
		<li><a href="" class="link-4"></a></li>
	</ul>
	<div id="menu-button"></div>
</nav>

What else?

You can tell Emmet the text you want between any of the tags, and even tag attributes. Here’s an example of the two features:

In your editor:

h2{Hello World}+p{From Emmet with love.}[tab]
img[alt="This is an alt text"][tab]

Should expand to:

<h2>Hello World</h2>
<p>From Emmet with love.</p>
<img src="" alt="This is an alt text" />

There are lots more shortcuts you can explore by going to http://docs.emmet.io and there’s a really good cheat sheet you can bookmark for reference.

Stay tuned for future articles where we will look at Emmet for writing CSS.

Until then have fun, and happy expanding.