Ruby on Rails Getting Started With JBuilder

Ruby on Rails Getting Started with JBuilder

In the past, it could be really cumbersome to build proper JSON data feeds. Fortunately Ruby on Rails makes dealing with JSON much easier. Today we will learn how to use the JBuilder gem, which will allow us to easily build complex data feeds.

First, we need to include the gem in our gemfile. Recent versions of Ruby on Rails include this gem commented out towards the bottom of the file. In addition, Rails 4 already includes this gem so you don’t need to do anything. If it is in your gemfile and it is commented out, uncomment it, otherwise, add the gem using the line shown below.

Gemfile
1
gem 'jbuilder', '~> 1.2'

Then run a bundle install:

1
bundle install

Next, we will need a model and some sample data. In this sample project we will have 2 models. A product model, and a review model, which will be associated with products. Lets generate these 2 models now. Run the commands below to create the models and migrate the database:

1
2
3
rails g model Product name price:decimal{12,2} active:boolean
rails g model Review product:references user rating:integer body:text
rake db:migrate

Excellent, Now lets add some seed data. Copy and paste the following seed data into your seeds.rb file:

db/seeds.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Product.delete_all
Review.delete_all

Product.create!([
  {id: 1, name: "Nintendo Wii U Premium", price: 250, active: true},
  {id: 2, name: "XBox 360 250GB", price: 250, active: true},
  {id: 3, name: "Playstation 3 500 GB", price: 239.95, active: true},
  {id: 4, name: "Nintendo Wii", price: 99.95, active: true},
  {id: 5, name: "Nintendo 3DS", price: 174.95, active: true}
])

Review.create!([
  {id: 1, product_id: 1, user: "Bob", rating: 3, body: "dated graphics.  Overpriced.  However, the games are awesome."},
  {id: 2, product_id: 1, user: "Rich", rating: 4, body: "MARIO!  'nuff Said"},
  {id: 3, product_id: 2, user: "James", rating: 5, body: "Excellent value for the money."},
  {id: 4, product_id: 2, user: "Alison", rating: 5, body: "Love it!"},
  {id: 5, product_id: 3, user: "James", rating: 4, body: "Bigger hard drive then my XBox 360.  Weak user interface though."},
  {id: 6, product_id: 4, user: "Kay", rating: 1, body: "Extremely dated.  Don't buy.  Will be discontinued soon."},
  {id: 7, product_id: 5, user: "Jed", rating: 4, body: "Awesome handheld system, but a bit overpriced."}
])

Next, run the seed command to populate your database:

1
rake db:seed

Well, we now have a database populated with products and reviews. Next we will need to set up the association between our products and our reviews. First, open up the Product model and modify it so that it looks like the code listed below:

app/models/product.rb
1
2
3
class Product < ActiveRecord::Base
  has_many :reviews
end

Great, now lets add the reverse association. Open up your Review model and verify that it looks like the code listed below. Rails should auto populate this, but double check just to be sure.

app/models/reviews.rb
1
2
3
class Review < ActiveRecord::Base
  belongs_to :product
end

With the database model created, our data populated, and our associations set up, now it’s time to create a controller. Run the command below to create products controller.

1
rails g controller products index

Now, lets make a change to our routes.rb file so that our controller becomes a resourceful controller. Replace the line that says get “products/index” with the code listed below.

config/routes.rb
1
2
# get "products/index"
resources :products, only: [:index]

This sets up the products controller as a resourceful controller. Now, in order to create a json feed using jbuilder, we must create a jbuilder view. Create a new file in app/views/products called index.json.jbuilder and add the code listed below.

app/views/products/index.json.jbuilder
1
2
json.products do
end

Excellent. Now if you navigate to http://localhost:3000/products.json You will see an empty json data feed. Now, lets add some content to that data feed. Now, open up the products controller and modify it so that it looks like the code listed below.

app/controllers/products_controller.rb
1
2
3
4
5
class ProductsController < ApplicationController
  def index
    @products = Product.all
  end
end

Next, Open the jbuilder file again and modify it so that it looks like the code listed below.

app/views/products/index.json.jbuilder
1
2
3
4
5
json.products @products do |product|
  json.name product.name
  json.price number_to_currency product.price
  json.active product.active
end

Excellent, now if we refresh the page we will see a listing of products in json format. Now lets add the reviews. Modify your code so that it looks like the code listed below.

app/views/products/index.json.jbuilder
1
2
3
4
5
6
7
8
9
10
11
json.products @products do |product|
  json.name product.name
  json.price number_to_currency product.price
  json.active product.active

  json.reviews product.reviews do |review|
    json.user review.user
    json.rating review.rating
    json.body review.body
  end
end

Excellent! Now if we refresh the page we’ll see the review listing for each product. That’s it folks! That’s all there is to using the jbuilder gem.

So far so good, That’s it!!! See ya!!! :)

10 Useful Ruby on Rails 4 Gems

10 Useful Ruby on Rails 4 Gems

The Ruby on Rails framework is an extremely powerful tool for developing web applications. It comes with plenty of built-in features which help accelerate the development of your web application such as intelligent routing and an object-relation mapper, all using an MVC pattern.

Rails is designed in a way to be very easily extended using Ruby gems. This has created a large ecosystem of Ruby gems which can extend your application and accelerate your development process even more by reducing the time involved working in developing common functionality. We’re going to go over a few gems which we consider to be very useful.

Devise
Devise is most probably the most commonly used Gem when using Ruby on Rails. It provides an easy-to-use authentication solution for your Rails application which will allow you to get login, registration, forget password, account locks and much more account-related features by simply using this Gem.

Pundit
It’s important to know the distinction between authentication and authorization. Devise helps authenticate users and verify who they are while authorization ensures that the user is allowed to perform an action or access a resource. Pundit takes care of this entire process by providing a simple way of defining authorization systems using nothing but Ruby classes.

Slim
There are many template systems out there. Ruby on Rails uses the eRuby template system by default, however, it’s typically something that users will choose to replace. Slim is a common replacement because it allows you to maintain very easy to read templates due to it’s simple syntax while maintaining very fast compilation times.

Draper
Draper allows you to build decorators around your models. It helps make your views much cleaner and lets you avoid writing helpers. Instead of procedurally calling helpers with models, you instead define a decorator which wraps the original model and provides a list of extended method and attributes to your object.

Cells
You’ll often re-use many components of your application. Typically, partials are used for this type of behavior however you must make sure that your controllers that call the partial all have consistent behavior. Cells allow you to take parts of your controller and encapsulate them into their own little controller. This helps make your code much cleaner and avoid the long helper/partial/filter mes.

FriendlyId
Typically, resources URLs are identified by their primary key which is usually their database ID. However, this can result in unoptimized web page URLs which are not user-friendly to read either. FriendlyId can easily transform your URLs to much friendlier and easy to remember URLs for little to no code changes in your web application.

Simple Form
Forms are at the heart of every single web application. If there is any level of interaction with the user, it typically is done using a web form. Simple Form helps simplify this very simple yet repetitive task. By implementing a simple and easy to use DSL for building forms, you can spend less time writing HTML for your forms and more time on the core business logic of your application.

Paperclip
File attachments are never easy to work with. They typically involve a significant amount of work to implement and even more time to make sure that they are implemented in a very secure manner. Paperclip takes care of this entire process for you inside your Rails application and extends it even more to things like transforming images to thumbnails and much more.

Kaminari
Kaminari is not a very descriptive name for a Gem, however, it is one of the most popular Gems with almost 5 million downloads. It enables you to paginate anything from ActiveRecord relations to simple arrays using a clean, easy to use and simple scope-based API which is fully agnostic to whatever ORM or template engine you use.

Sidekiq
There are many choices for background processing tools when using Ruby on Rails, however, Sidekiq is the one of the most popular ones. The reason behind it’s popularity is the simplicity of it’s API and how it scales much better than other background processors.

So far so good, That’s it!!! See ya!!! :)

How to Install Rails and Nginx With Passenger on Ubuntu?

How To Install Rails and Nginx with Passenger on Ubuntu?

Ruby on Rails is an open source web application framework which runs on the Ruby programming language. It allows the developers creating pages and applications that gather information from the web server, talk to or query the database, and render templates out of the box directly to the internet browsers.

As a result, Rails features a routing system that is independent of the web server. The web server is used to render the content only. The choice for that would be Nginx. Nginx is fast webserver with a strong focus on high concurrency, high performance and low memory usage.

Install Ruby and Rails

Before we proceed with installation, we should make sure that our system repositories are up to date:

1
sudo apt-get update

Once we are up to date with the latest available packages, the next step is to install Ruby Version Manager. It is application that allows to manage several different ruby versions easily, we can install RVM and then load it with:

1
2
curl -L get.rvm.io | bash -s stable
source /usr/local/rvm/scripts/rvm

We must make sure that we have all dependencies from RVM. To make sure that we have all required dependencies, we execute the following command:

1
rvm requirements

It will make sure that we are up to date and install the missing requirements (if any). Once we have RVM installed and configured, we can proceed to install and configure Ruby.

1
2
rvm install 2.1.1
rvm use 2.1.1 --default

These two commands will install Ruby and set the system to use version 2.2.1 by default. The next step is to make sure we have all components for Ruby on Rails. Ruby Gems is a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries, a tool designed to easily manage the installation of gems, and a server for distributing them, we can install it with this command and then use it to install Rails:

1
2
rvm rubygems current
gem install rails

This process could take some time, but after it finish, Ruby on Rails is installed.

Install Passenger and Nginx

We need to make sure that we can easily deploy Ruby on rails to any web server. We will install and use Passenger for that. It will serve as interface or bridge for communication between Ruby and the web server, you can install it with the following command:

1
gem install passenger

Once passenger is installed, the rest of the required setup is fully automated. We execute the command:

1
rvmsudo passenger-install-nginx-module

Once we do this, it checks for all dependencies automatically and install those that are missing. If some manual user action is required, Passenger will tell us, as well as give us detailed instructions how to do it.

Now we need to configure nginx to “talk” to Passenger. In order to do that, we need to open the nginx configuration file (/opt/nginx/conf/nginx.conf), using our favorite editor and add the following:

nginx.conf
1
2
3
4
5
6
server {
  listen 80;
  server_name example.com;
  passenger_enabled on;
  root /var/www/rails_app/public;
}

In order to create our rails app, we need to install Node.js first:

1
sudo apt-get install nodejs

Once that is that, we should go to our directory (in this case it is /var/www/rails_app/public) and create the application. After all this is installed and configured, we simply need to start Nginx.

1
2
rails new my_first_rails_app
sudo service nginx start

We can try and access our new Ruby on Rails application using our browser. It seems that it was much easier to setup the environment and create our first Ruby on Rails project than we thought.

So far so good, That’s it!!! See ya!!! :)

Ruby on Rails Build a Simple Rake Task

Ruby on Rails Build a Simple Rake Task

There are many tasks that need to be performed outside of your website that are related to your web application. An example would be cleaning up temporary files. You wouldn’t want to have this code running in a web page. Fortunately rails includes a mechanism for doing this. Rake tasks make it easy to automate various aspects of your application.

First, we need to create a couple models for our sample. In this sample we will have 2 models. Our first model, Product, will store product information. Our second model, Review, will be a review of the product. Run the commands below to generate these 2 models:

1
2
3
rails g model Product name average_rating:float price:decimal{12,2} active:boolean
rails g model Review product:references user rating:integer body:text
rake db:migrate

Next, we need some seed data. Open up your seeds.rb file and add the following code:

db/seeds.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Product.delete_all
Review.delete_all

Product.create!([
  {id: 1, name: "Die Hard - Blu-Ray", price: 9.95, active: true},
  {id: 2, name: "Iron Man 3 - Blu-Ray", price: 24.95, active: true},
  {id: 3, name: "Star Trek - Into Darkness - Blu-Ray", price: 19.95, active: true},
  {id: 4, name: "The Little Mermaid - Blu-Ray", price: 29.95, active: true},
  {id: 5, name: "This is the End - Blu-Ray", price: 17.95, active: true}
])

Review.create!([
  {id: 1, product_id: 1, user: "Dan", rating: 5, body: "Epic Action Flick"},
  {id: 2, product_id: 1, user: "Will", rating: 4, body: "The Stunts were AMAZING!"},
  {id: 3, product_id: 2, user: "James", rating: 2, body: "I didn't like it as much as the first one."},
  {id: 4, product_id: 2, user: "Lisa", rating: 5, body: "Epic!"},
  {id: 5, product_id: 3, user: "Linda", rating: 5, body: "A classic revived!  Well worth watching again."},
  {id: 6, product_id: 4, user: "Kathy", rating: 5, body: "This movie is hilarious!"},
  {id: 7, product_id: 5, user: "Jim", rating: 3, body: "Really cheesy."}
])

Then run rake db:seed

1
rake db:seed

Now, lets open up the Product model so that we can add an association to reviews. Modify the Product model so that it looks like the code listed below:

app/models/product.rb
1
2
3
class Product < ActiveRecord::Base
  has_many :reviews
end

Then create a file called calculate_averages.rake in the lib/tasks folder and add the following code:

lib/tasks/calculate_averages.rake
1
2
3
4
5
6
7
8
9
10
require 'rake'

task :calculate_averages => :environment do
  products = Product.all

  products.each do |product|
    puts "Calculating average rating for #{product.name}..."
    product.update_attribute(:average_rating, product.reviews.average("rating"))
  end
end

Now, if we run our rake command we will see that the averages are updated in the database.

1
rake calculate_averages

So far so good, That’s it!!! See ya!!! :)

Add Google Analytics to Ruby on Rails Application

Add Google Analytics to Ruby on Rails Application

Google Analytics is used by the vast majority of the internet to monitor traffic. You can quickly and easily add Google Analytics to your Rails application, however there are a few things you should pay attention to. First, make sure that the Analytics code only loads up in a production environment. It’s best to do this by first creating a partial called google_analytics and placing the following code inside of it:

app/views/layouts/_google_analytics.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<% if Rails.env == "production"  %>
  <script type="text/javascript">

    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-00000000-1']);
    _gaq.push(['_trackPageview']);

    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

  </script>
<% end %>

This code will tell Rails to only include the Analytics code in a production environment.

So far so good, That’s it!!! See ya!!! :)

Ruby on Rails Generate Options

Ruby on Rails Generate Options

There are many useful rails generate commands. I’ve listed some of them below for your reference:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Creates a model and controller, then adds a resource route to your routes.rb file.
rails g resource <attribute>:<type>  <attribute>:<type>

# Just like rails g scaffold, but doesn't create the model.
rails g scaffold_controller <name>

# Creates a coffeescript/javascript and corresponding (s)css file.
rails g assets <name>

# Creates a jbuilder file
rails g jbuilder <name> <field>:<type> <field>:<type>

# Creates a custom helper.
rails g helper <name>

# Allows you to create your own custom generates to be used with rails generate.
rails g generator <name>

# Creates a rake task.
rails g <namespace> <task_name> <task_name>

For a complete list of all generate commands, simply run rails g or rails generate from within a project.

So far so good, That’s it!!! See ya!!! :)

Ruby on Rails Web Console

Ruby on Rails Web Console

As you know, Ruby on Rails has long included the ability to load up an interactive console environment for your application. Simply running rails c would start this console, which allows you to do things like ActiveRecord queries, troubleshooting, and much more. Since the full Rails stack gets loaded you have access to pretty much anything your application has access to. This is useful to troubleshoot things on the spot.

Starting with Ruby on Rails 4.2, developers will have access to a web based version of this console. The good news is that you don’t have to wait for Ruby on Rails 4.2 to hit in order to take advantage of this awesome capability. You can quickly and easily use the web console in your current Rails application by performing the steps below.

Setup
To use the Rails web console, we need to include the web-console gem. Simply add the line below to your Gemfile, then run a bundle install to install it.

Gemfile
1
2
3
group :development do
  gem 'web-console', '~> 2.0'
end

Terminal Commands:

Gemfile
1
bundle install

Next, we need to turn on the web console in our application configuration. To do this, simply add the following line to your development.rb environment file:

config/environments/development.rb
1
config.web_console.automount = true

Now, let’s create a controller to play with the console. Run the command below to create a controller that we can use to play around with the console. For this example, we will create a controller called Homes with a method called show.

Terminal Commands:

1
rails g controller Homes show

Now, open up your routes file and modify it so that it looks like the code listed below:

config/routes.rb
1
2
3
Rails.application.routes.draw do
  root to: "homes#show"
end

Now open up the show view for the Homes controller and add in the code listed below:

app/views/homes/show.html.erb
1
<%= console %>

If you start a rails server and navigate to your development environment, you’ll notice that there is a console at the bottom of the screen. You can execute Ruby and Rails code here. The console is running within your Rails application so pretty much anything goes.

By default, console application is mounted to http://yoursite/console. However, what if we wish to change the path? We can easily do it by adding the line listed below to our development.rb file:

config/environments/development.rb
1
config.web_console.default_mount_path = '/your/favorite/path'

Whitelisting IPs
The console by default only works with if you are accessing it locally via 127.0.0.1. If you are on a network or using a VM, you may need to add your ip to a whitelist. You can easily do that by adding the line listed below to your development.rb file. Don’t forget to restart your Rails server for changes to take effect.

config/environments/development.rb
1
config.web_console.whitelisted_ips =  %w( 127.0.0.1 192.168.0.100 )

You can also add an entire subnet. Remember to make sure you add 127.0.0.1 or the local machine won’t have access.

config/environments/development.rb
1
config.web_console.whitelisted_ips =  %w( 127.0.0.1 192.168.0.016 )

Run Other Commands
By default the console runs the rails console. However, you can have it run another command instead. For instance, we can turn the web console into an terminal running bash by adding the following line to our development.rb file:

config/environments/development.rb
1
config.web_console.command = 'sudo /bin/login'

Be aware that passwords sent using this method are sent in plaintext. if that concerns you, you should consider using SSL.

Security Considerations
At this point, it’s not advisable to run this on production. Exposing the console endpoint in a production environment means anyone can get access to the Rails console and therefore access to the system itself. Stick to the development/test environments. Hopefully in the future the Rails team will provide additional features that will allow console use in a production environment.

As mentioned earlier, console information is sent plain text. If this concerns you, consider using SSL or not using the web console.

So far so good, That’s it!!! See ya!!! :)

Hash Data in Ruby

Hash Data in Ruby

Somethings we need to utilize hashing algorithms in Ruby and/or Rails. Examples of this include verifying file integrity, hashing passwords, and much more. In this brief article we will show you how to hash data in various formats.

Calculate an MD5 Hash
The venerable MD5 algorithm is an older and simpler hashing algorithm. Please note that MD5 is considered insecure due to the fact it can be brute forced relatively quickly, so you should use this algorithm with extreme care. To use MD5, simply use the following code:

1
hash = Digest::MD5.hexdigest("this is a test") # => "54b0c58c7ce9f2a8b551351102ee0938"

Calculate a SHA-1 Hash
SHA-1 hashes are much more secure. SHA-1 can be used for passwords and file hashing, but it’s recommended that you move to SHA-2 (SHA256, SHA384, and SHA512) as soon as you can as they are even more secure. SHA-1 is also an excellent choice for maintaining file integrity.

1
hash = Digest::SHA1.hexdigest("this is a test") # => "fa26be19de6bff93f70bc2308434e4a440bbad02"

Calculate a SHA-2 hash: SHA256, SHA384, and SHA512
HA-2 includes a number of different digest lengths, with SHA-512 in theory being the most secure. Calculating these hashes is just as easy.

1
2
3
4
5
Digest::SHA256.hexdigest("this is a test") # => "2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c"

hash = Digest::SHA384.hexdigest("this is a test") # => "43382a8cc650904675c9d62d785786e368f3a99db99aeaaa7b76b02530677154d09c0b6bd2e21b4329fd41543b9a785b"

hash = Digest::SHA512.hexdigest("this is a test") # => "7d0a8468ed220400c0b8e6f335baa7e070ce880a37e2ac5995b9a97b809026de626da636ac7365249bb974c719edf543b52ed286646f437dc7f810cc2068375c"

So far so good, That’s it!!! See ya!!! :)

Ruby on Rails Export CSV

Ruby on Rails Export CSV

Sometime you will want to provide a CSV export option for your users. This article will show you how.

The first thing we need to do is open up the config/application.rb file and add:

config/application.rb
1
require 'csv'

Next, we need to add some code to the model that will export the data in the CSV format. Add the following code to the model you wish to export to CSV:

1
2
3
4
5
6
7
8
def self.as_csv
  CSV.generate do |csv|
    csv << column_names
    all.each do |item|
      csv << item.attributes.values_at(*column_names)
    end
  end
end

This code will export both the column headers as well as the data in the csv format and return the result.

Finally, we need to add a bit of extra code to our controller in order to return the CSV data to our user. Assuming your model and controller are named posts, add the following code to your posts controller:

1
2
3
4
5
6
7
8
def index
  @posts = Post.order(:created_at)

  respond_to do |format|
    format.html
    format.csv { send_data @posts.as_csv }
  end
end

Now, if you visit http://localhost:3000/posts.csv, you will be prompted to download the CSV.

So far so good, That’s it!!! See ya!!! :)

How to Build a Sitemap for Your Ruby on Rails Application

How to Build a Sitemap for Your Ruby on Rails Application

Sitemaps are a valuable tool for telling search engines about the structure of your website. Creating a sitemap and submitting it to the search engines can let Google or Bing know about the pages they have missed when they crawled your site. In addition, submitting a sitemap can speed up crawl times significantly.

In this article we will show you how to build your own sitemap which you can then submit to the various search engines.

Rails Application Setup
We are going to build a very simple blog. First we will build the blog itself, then we will add the functionality needed for the sitemap. Don’t worry, this won’t take long.

First let’s create our models. We only need one model for this example, Post. The Post model is simply an instance of a blog entry. Run the commands below to create the Post model now:

1
2
rails g model Post title body:text
rake db:migrate

Great, now let’s create our controllers. In this example we will have two controllers. The Posts controller lists our posts and lets us view individual posts, and the Sitemap controller actually generates the sitemap. Run the commands below to create these controllers now:

1
2
rails g controller Posts index show
rails g controller Sitemap index

Now let’s add our routes. Open up your routes file and modify it to look like the code listed below. Be sure not to overwrite line 1 of your routes file with line 1 of the example code listed:

config/routes.rb
1
2
3
4
5
SitemapExample::Application.routes.draw do
  resources :posts, only: [:index, :show]
  resources :sitemap, only: [:index]
  root to: "posts#index"
end

Now let’s add code to our controllers. First let’s add the code necessary to list and display posts to the Posts controller. Open up your Posts controller and modify it so that it looks like the code listed below:

app/controllers/posts_controller.rb
1
2
3
4
5
6
7
8
9
class PostsController < ApplicationController
  def index
    @posts = Post.order("created_at DESC")
  end

  def show
    @post = Post.find(params[:id])
  end
end

Now lets add code to our Sitemap controller. The only code we need here is code to list the posts. Open up your Sitemap controller and modify it so that it looks like the code listed below.

app/controllers/sitemap_controller.rb
1
2
3
4
5
6
class SitemapController < ApplicationController
  respond_to :xml
  def index
    @posts = Post.order("created_at DESC")
  end
end

Now let’s create the views. First lets create the index view for the Posts controller. Open up the index view and modify it so that i looks like the code listed below.

app/views/posts/index.html.erb
1
2
3
4
5
6
7
8
9
10
<h1>My Blog</h1>
<%  @posts.each do |post| %>
  <h3><%= link_to post.title, post %></h3>
  <p>
    <%= post.body.html_safe %>
  </p>
  <% if post != @posts.last %>
    <hr />
  <% end %>
<% end %>

Now let’s create the show view. Open up the show view for the Posts controller and modify it so that it looks like the code listed below.

app/views/posts/show.html.erb
1
2
3
4
<h1><%= @post.title %></h1>
<p>
  <%= @post.body.html_safe %>
</p>

Now it’s time for the sitemap. A sitemap is an XML file that typically consists of a number of url xml elements encapsulated by a urlset xml element. Each url typically has the 4 elements listed below.

XML Description
loc The actual url to the page you wish to list in the sitemap.
changefreq How often the page changes, can be always, hourly, daily, weekly, monthly, yearly, or never.
priority How important the page is within the context of your site.
lastmod The date of the last modification of this page.

An example sitemap is listed below:

sitemap.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://localhost:3000/</loc>
    <changefreq>hourly</changefreq>
    <priority>1.0</priority>
  </url>
  <url>
    <loc>http://localhost:3000/posts/2</loc>
    <changefreq>daily</changefreq>
    <priority>0.8</priority>
    <lastmod>2014-03-04T17:01:15.37+00:00</lastmod>
  </url>
  <url>
    <loc>http://localhost:3000/posts/1</loc>
    <changefreq>daily</changefreq>
    <priority>0.8</priority>
    <lastmod>2014-03-04T17:01:15.36+00:00</lastmod>
  </url>
</urlset>

This example was generated from our application. To do this yourself, create a new view for our Sitemaps controller called index.xml.builder and add in the code listed below.

app/views/sitemap/index.xml.builder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
xml.instruct!

xml.urlset(xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9") do
  xml.url do
    xml.loc root_url
    xml.changefreq("hourly")
    xml.priority "1.0"
  end
  @posts.each do |post|
    xml.url do
      xml.loc post_url(post)
      xml.changefreq("daily")
      xml.priority "0.8"
      xml.lastmod post.updated_at.strftime("%Y-%m-%dT%H:%M:%S.%2N%:z")
    end
  end
end

The first xml.url block adds an entry for our root url. In a more complex application we would probably want to add static entries for other pages. The next thing the code does is loop through each post and create a xml url element for each.

You can preview your sitemap by starting your rails server and visiting http://localhost:3000/sitemap.xml.

So far so good, That’s it!!! See ya!!! :)