How to Build a JSON Feed for Your Rails Application

Last week we looked at how to build an RSS feed for your Rails application. RSS is a stalwart and one of the early technologies of the Internet. JSON Feed, however, is a new take on the the existing RSS format. While RSS uses XML to build a feed, JSON Feed uses the simpler and more readable JSON, short for JavaScript Object Notation.

20 years ago XML was a perfectly suitable choice for creating RSS feeds, but over the years developers have gradually started using alternatives to XML. One such alternative is JSON. Its simple syntax and structure make it easy for developers to work with and is commonly used in APIs all over the Internet. JSON Feed was developed by Manton Reece and Brent Simmons as a more developer-friendly way of building RSS feeds.

JSON feeds serve the same purpose as RSS feeds: They provide a file that lists the most recent changes to a website or collection of articles. JSON Feed is only a few months old, but RSS feed readers like Feedbin have already begun adding JSON Feed compatibility.

How do you add a JSON feed to a Ruby on Rails application, then?

In this example we’re using the same route, controller and action as the RSS feed we used in the previous example. For the purpose of this article, we’re going to have just one feed in our Rails application, the JSON feed.

Define the route

Like RSS feeds, we need to define a route for our JSON feed. In our Rails application’s routes.rb file, we’re going to define the route to our JSON feed.

get '/default.json', to: 'feeds#index'

Create a controller for your feed

Right, we have our route defined. Next we want to connect the route to our ActiveRecord model that represents the changes in the website. Let’s create a controller to do that.

Just like our RSS feed, we’re going to create a feeds controller and give it an index action that will serve the content for our feed.

class FeedsController < ApplicationController
  def index
    @posts = Post.published

    respond_to do |format|
      format.json { render layout: false }
    end
  end
end

We’re responding to the index action’s request with a JSON file, so the respond_to block will use the .json method to return the content in the correct format.

Just like an RSS feed, we’re rendering the response without a layout. There’s nothing to the JSON feed file other than its own content. We don’t need a layout for this.

Create the view to return the feed

Last but not least is the view file that will contain the content of the feed in a format that meets the requirements of the JSON Feed standard. This means that the file will use a json extension and will differ slightly in the syntax used.

The view file will contain a number of elements similar to those of an RSS feed.

  • a unique identifier for the article
  • the body of the article
  • a link to the article

Your view file will look something like this:

json.version 'https://jsonfeed.org/version/1'
json.title 'ACME Content'
json.home_page_url root_url
json.feed_url 'https://www.acmecontent.net/feed.json'

json.items @posts do |post|
  json.id post.id
  json.context_text post.title
  json.url post_url(post)
end

You’ll notice that the JSON feed has a lot less in it than the RSS feed example. For the purposes of this article, we are using a simple version, but even a more detailed JSON feed would still be quite simple.

Where your RSS feed view file has an .rss.builder extension, this view file will use a .json.jbuilder file extension. We’re using the JBuilder gem to generate our view file contents.

Finally, let’s make our JSON discoverable.

<%= auto_discovery_link_tag(:json, { controller: 'feeds/default', action: 'index' }, { title: 'Recent prompts', type: 'application/json' }) %>

This differs slightly from an RSS feed in that we’re defining the response type because it’s going to be a JSON response.

What are the benefits?

While the adoption of the JSON Feed standard is still growing, you might question the benefit of adding a JSON feed to your Rails application.

There are many arguments for and against all standards used on the Internet, but I lean towards open standards that make accessibility of web sites and applications easy. It’s for that reason that while I would recommend adding a JSON feed to your website, it’s not an urgent thing to do. It’s just more of a nice thing to have.

If you’re building a web-based product, though, that uses feeds as a delivery method for content, then I would definitely put this nearer the top of your product’s next feature list.

The JSON Feed standard is still young, but as a more developer-friendly version of RSS, it’s worth looking into, especially if you know the consumers of your feeds are using JSON Feed compatible feed readers.

With new technology it’s always a case of ensuring there is high enough adoption before you start learning and using that technology yourself. However, the ease with which you can add a JSON feed into your Rails application means that it’s a low-risk feature that can be added to most Rails applications in little time.

How to Build an RSS Feed for Your Rails Application

RSS has been overlooked as an Internet technology for the last few years. The rise of social media platforms has seen RSS uptake fall, but that doesn’t mean it’s not something to leave out of your Ruby on Rails application.

An RSS feed is simply a file that lists the most recent changes to a website or a collection of articles. A lot of websites still utilise RSS feeds, and a lot of CMS platforms have this baked right into the system.

How do you add an RSS feed to a Ruby on Rails application, though?

Define the route

The first thing we need to do is define a route for it. The route is the endpoint for the RSS feed, and it’s what others will look for when subscribing to your site. In our application’s routes.rb file, we define a route to our feed.

get '/default.rss', to: 'feeds#index'

Create a controller for your feed

The next step in the process is to connect the endpoint to the ActiveRecord model that we want to see the changes for.

From our route we need to define a feeds controller and add to it an index action that will serve the content for our feed.

class FeedsController < ApplicationController
  def index
    @posts = Post.published

    respond_to do |format|
      format.rss { render layout: false }
    end
  end
end

Nothing here that you haven’t done before, but one thing to note is that we don’t want to render a layout with our feed, so we pass false to the layout option when rendering our feed.

You don’t have to use a new controller for this. If you already have a controller that is accessible from the Internet and delivers the same content but to the browser, then you can use the existing controller to also deliver the feed.

class PostsController < ApplicationController
  def index
    @posts = Post.published

    respond_to do |format|
      format.html { render :index }
      format.rss { render layout: false }
    end
  end
end

Create the view to return the feed

Finally, there’s the creation of the view. The view is typically what the end-user sees in a Rails application, but in this case it’s going to be what the RSS reader sees.

The view is going to be an XML file that will contain a number of elements typically found in an RSS feed. These are:

  • A unique identifier for the article
  • A title for the article
  • The body of the article
  • Timestamps for the article

The view will look something like this:

xml.instruct! :xml, :version =\> '1.0' 
xml.rss :version =\> '2.0' do
  xml.channel do
    xml.title 'ACME Content'
    xml.description 'Our latest posts'
    xml.link root_url

    for post in @posts
      xml.item do
        xml.title post.title
        xml.description post.body
        xml.pubDate post.published_at.to_s(:rfc822)
        xml.link post_url(post)
        xml.guid post.id
      end
    end
  end
end

There’s a couple of things to note here.

The view uses a .builder extension rather than an .erb extension. The reason for this is we’re using the Builder gem to format our feed into XML.

We’re using an RFC format of the date to help validate the feed.

We haven’t included this in the view file, but you can cache your RSS feed for a period of time so that feed readers aren’t continually hitting the endpoint and in turn hitting your database.

Auto-discovery feeds

Have you noticed when you subscribe to a website using an RSS reader that for some sites you can just pass in the website URL and their RSS feed will be determined from this?

Well, the reason this works is that the website contains a link that tells the RSS reader where the sites RSS feed is.

So how do we do this in Rails?

Well, it’s quite simple. By using the auto_discovery_link_tag we can add our site’s RSS feed to the HTML mark-up so that RSS readers can get it.

<%= auto_discovery_link_tag(:rss, { controller: 'feeds/default', action: 'index' }, { title: 'Recent articles' }) %>

Testing strategy

Ideally, we would write some tests to ensure that the endpoint is responding with a success code and that the response itself contains the right elements for the RSS subscriber to see. A single controller test for this will suffice.

What are the benefits?

Not only a subscription channel to your website, RSS can be used as an integration endpoint for subscribers and other platforms.

Two platforms that spring to mind are IFTTT and Zapier. Both of these platforms have channels that can act on new items published to an RSS feed.

Social media automation is one way of utilising this, and it gives you more control over what to filter through to your social media channels as well.

RSS is an early Internet technology, but its usefulness is often overlooked. As a way for people to subscribe to your website, it’s the first step in attracting people to your website, and the easiest one for people to engage with.

Single or composite primary key in Rails?

When it comes to Ruby on Rails applications, most of the time we create database tables for models with a single primary key. The reason for this is that most of the models we need have basic create, read, update and destroy actions on them, so a unique identifier for each record makes sense.

Let’s take this case a step further.

We have a table of product discounts. Each product discount has an associated product and discount. Product discounts are managed from a series of screens where users can create, read, update and destroy product discounts. There is a crucial constraint though: Each product can only have one discount at any one time.

Using a single primary key

The most obvious solution is to have a table that has a single primary key on it with two extra foreign key fields for the product id and the discount id.

Product Discount ID Product ID Discount ID
1 1001 2001
2 1002 2002
3 1003 2003

The benefit to this table design is that there is a single primary key on the table that allows us to access product discounts as a RESTful resource in the Rails application. With a single primary key we can have a fairly succinct path to this resource.

/product_discounts/1

The drawback to this is that we still need to add validation to the product discount model so that only one product has a single discount at any one time, as we lack the constraints to do this in the database.

Breaking out the composite primary key

Let’s take out the idea of the product discounts having a single primary key and instead use the product id and discount id to create a composite primary key for the product discounts table.

Composite primary keys are effectively two primary keys rolled into one. Rather than having a single identity column that has a unique key for each record, composite primary keys consist of two identity columns that use the pairing of the two to determine if a record is unique or not.

Product ID Discount ID
1001 2001
1002 2002
1003 2003

The benefit of this table design is that we now have a primary key that is unique for each combination of product id and discount id. At no point can a product have more than one discount at a time, even if the data came from an external source other than our Rails application.

There is a drawback, though, and that’s the idea of having a simple RESTful resource in the application that has a succinct path. Instead of our product discounts path,

/product_discounts/1

we would have a longer path that encompasses both parts of the primary key:

/products/1001/discounts/2001

Or even:

/discounts/2001/products/1001

Single or composite primary key?

If we put aside the constraints on the database and handle our data validation through Rails ActiveRecord, it’s clear that the easiest solution is to use a single primary key.

We have the benefit of being able to manage the product discounts through a single RESTful resource with succinct paths for the product discounts and a single identification value for each product discount.

If we need constraints on the database, then I would go for a composite primary key. It adds the layer of validation to the database itself. It also means that if the database has any external data sources, then having a composite primary key on the product discounts table keeps the product discount data valid.

We will have to handle the product discounts in a slightly more complicated way instead of having a single RESTful resource for them. It’s only one resource level deeper, and it’s worth the trade-off of having constraints in the database to make sure the data is always valid.

A case for both

There are cases for both a single primary and a composite primary key. What I tend to look for is whether the table is in fact going to be a join table or a RESTful resource in its own right.

Sure we could pull up a product page and then manage all the discounts for that product, or even vice versa, but if the idea that a product discount is a resource in its own right, then I would use a single primary key to make sure that each product discount has an identifier for that product discount. Also, it’s worth considering if there will be associations for these product discounts elsewhere in the Rails application.

A composite primary key comes into its own when we need data consistency on a database level, especially if there are other external applications using the database that we have limited control over.

When it comes to deciding on the right keys for your models, take a look at the surrounding models of your application and consider associations between these models and the new model you are about to create. You should also consider external sources to the database and decide if data consistency at a database level is needed.

It can be easy to always use a single primary key for your models, but there’s a benefit to using composite primary keys when used in the right way.

Creating a Sitemap with Ruby on Rails

One of the easiest ways that you can improve your search engine rankings is by creating a sitemap of your SaaS product and submitting it to search engines. Sitemaps don’t replace the crawlers search engines use to index sites, but they can help those crawlers by providing extra metadata on the urls that make up your site, such as how often those pages are updated.

If your site has content that changes over time, it helps to keep your sitemap updated so that search engines will be notified of those changes.

Let’s build a basic sitemap for a Ruby on Rails application.

Add a route for the sitemap

Using an “outside in” approach, we’ll start with the necessary route for the sitemap by updating the routes file, routes.rb.

get 'sitemap', to: 'sitemap#index', constraints: { format: 'xml' }

We only need the index action for our sitemap, so we can specify that the route uses the index action only. We also define a constraint on the route so that it only accepts XML requests which will be for the format of our sitemap file.

Add a controller for the sitemap

Now we’ll create a controller for our sitemap.

class SitemapController < ApplicationController
end

A sitemap is an XML document, so we’ll need to tell the action that we want to respond to any requests to the controller with XML. We can do that with the respond_to method on the controller.

Add an action that renders the sitemap

Next we’ll add the index action for our controller.

def index
  respond_to do |format|
    format.xml
  end
end

A sitemap is an XML document, so we’ll need to tell the action that we want to respond to any requests to the action with XML. We can do that with the respond_to block on the action.

We’ll define the list of pages within the sitemap view (see below) rather than in the controller. We’ll set this up with the typical set of pages that can be found in most SaaS products, but if you have any other pages, feel free to add them in a similar fashion.

Add the sitemap view

Next we’ll add the view for our sitemap.

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  <url>
    <loc><%= root_url %></loc>
    <changefreq>weekly</changefreq>
  </url>
  <url>
    <loc><%= new_signup_url %></loc>
    <changefreq>weekly</changefreq>
  </url>
  <url>
    <loc><%= pages_url %></loc>
    <changefreq>weekly</changefreq>
  </url>
  <url>
    <loc><%= terms_url %></loc>
    <changefreq>weekly</changefreq>
  </url>
  <url>
    <loc><%= privacy_url %></loc>
    <changefreq>weekly</changefreq>
  </url>
</urlset>

What we have added here is a set of URLs that we want to submit to the search engine. Each URL is contained within a set of url tags The URL itself is within the loc tags, and the frequency with which we want the search engine to check the page is noted within the changefreq tag.

The valid options for the changefreq tag are hourly, daily, weekly, monthly, yearly, or never. If the page in question is unlikely to change very often, set the changefreq tag to monthly or even yearly. For other pages that change more frequently, like your key landing page(s), I recommend setting the changefreq tag to weekly.

Updating the sitemap

The sitemap contains a number of pages that aren’t likely to change or to be removed, but what about content that changes more frequently, like blog posts? Perhaps you have a blog on your SaaS product or even a group of product pages that are frequently updated. How do we include this changing content without having to manually amend the sitemap file each time?

With Ruby on Rails it’s simple to pass the pages through that you want to change, and update the sitemap with these changes.

Let’s say our SaaS product has a blog with a collection of posts that we use to highlight new features of the product and updates to it. We can amend the controller so that it returns all the posts in our blog.

class SitemapController < ApplicationController
  def index
    @posts = Post.all
    respond_to do |format|
      format.xml
    end
  end
end

Now that we have the posts as an instance variable, we can include it in our sitemap. Since this information changes on a regular basis, we’ll set each of our posts to have a changefreq of monthly.

In our sitemap we can now tell search engines about these new posts on our blog.

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  <url>
    <loc><%= root_url %></loc>
    <changefreq>weekly</changefreq>
  </url>
  <url>
    <loc><%= new_signup_url %></loc>
    <changefreq>weekly</changefreq>
  </url>
  <url>
    <loc><%= pages_url %></loc>
    <changefreq>weekly</changefreq>
  </url>
  <url>
    <loc><%= terms_url %></loc>
    <changefreq>weekly</changefreq>
  </url>
  <url>
    <loc><%= privacy_url %></loc>
    <changefreq>weekly</changefreq>
  </url>
  
  <% @posts.each do |post| %>
    <url>
      <loc><%= url_for(post) %></loc>
      <changefreq>monthly</changefreq>
    </url>
  <% end %>
</urlset>

Now each blog post we publish will automatically be added, and the sitemap will be kept up to date without adding these new posts manually. Nice!

Let’s deploy it!

Once our sitemap is complete, there’s the simple matter of deploying it to our preferred hosting stack and then submitting that sitemap to search engines. Bing allows you to submit your sitemap without any other requirements, but Google does require you to have a Google account before you can submit your sitemap to them.

You can also add your sitemap to your robots.txt file so that when a search engine crawls your site for new content, it will be redirected to the sitemap from the robots.txt file. You can include something like this in the file so that search engine crawlers can find your sitemap:

Sitemap: https://www.myamazingproduct.com/sitemap.xml

With a little investment in time and effort, your SaaS product can have a sitemap that updates on its own and requires little in the way of maintenance. Like all SEO recommendations, sitemaps aren’t the only solution to improving your search engine rankings, but they are one small change that will help round out your SEO strategy.

Helpful SEO Gems for your Ruby on Rails SaaS Product

There are two ways in which you can start making your Ruby on Rails SaaS product more SEO friendly.

The first and most obvious choice is to start using a gem. The benefit of using a gem is that you can get your product more SEO friendly in a short space of time. The drawback, though, is that your product will still need to be indexed, so while the fix itself is quick, it will still take time for your changes to be indexed in all the search engines you’re targeting.

The second choice is to roll your own set of helpers that make your SaaS product SEO friendly. The benefit here is that your product has one less dependency to worry about. Not only that, but if there’s any functionality you need to add to your SEO, it’s easier to make amendments to your own code rather than making your product work with a gem that doesn’t provide that functionality. The drawback is that you need to maintain another aspect of your product over time.

Deciding to roll your own SEO helpers will depend on your SaaS product and the different models that represent pages. That discussion is beyond the scope of this post and best reserved for a later date.

For now let’s take a look at a couple of gems that I recommend for adding SEO to your SaaS product.

FriendlyID

Search engine optimisation isn’t just about making your SaaS product search engine friendly, it’s also about making it easy for your landing pages to be read and interpreted by humans. This is where clean URLs and the FriendlyID gem come in.

If you have a landing page for your ACME dynamite blasting apparatus, the URL for that particular landing page might look like this:

https://www.acmedynamite.com/pages/4

The problem with this is that there is no clear description of what this page is from a human perspective. We know it’s the fourth page on the website, or a page with an ID of four, but other than that there is little information for us to discern what the page is about.

Let’s look at a more SEO friendly URL.

https://www.acmedynamite.com/blasting-apparatus-benefits/

It’s clear from this that the URL we visit includes the benefits of blasting apparatus for this particular dynamite company. This conveys a better meaning and description of the page to an interested potential customer. More interest means more views on that page. That’s definitely a start, but friendly URLs like this don’t have an effect on your search engine rankings. They do, however, make the links in the search engine result pages much more readable and easier to interpret from a human perspective.

FriendlyID offers many more features than clean URLs. With this gem you can version your URLs, scope them and even block users from using reserved words in their URLs.

MetaTags

The title of each landing page is everything. It’s included in the search engine results pages when search engines find your content. It’s the headline that attracts customers to your product, and, when written correctly, it could be the very thing that turns a guest to your product into a paying customer. Needless to say, page titles are important.

For a small micro-product, though, you might only have a handful of landing pages, maybe even just one or two. Managing these page titles is easy to do with a small Ruby on Rails application. What happens, though, if your product has a larger number of landing pages, and you want to make it easier to update all of them?

MetaTags is a gem for Ruby on Rails applications that provides a number of helpers for you to set the titles of your landing pages in a number of different ways.

You can set the site title of your SaaS product.

set_meta_tags title: 'Blasting Apparatus'

will render your landing page title as

<title>Blasting Apparatus</title>

You can set the site title and page title of your SaaS product.

set_meta_tags site: 'ACME Dynamite', title: 'Blasting Apparatus'

will render your landing page title as

<title>ACME Dynamite | Blasting Apparatus</title>

And lastly if you have a site title and page title, then you can reverse these so that the page title appears first.

set_meta_tags site: 'Site Title', title: 'Member Login', reverse: true

will render your landing page title as

<title>Blasting Apparatus | ACME Dynamite</title>

MetaTags also includes a number of other helpers for the description and keywords tags, as well as helpers to indicate whether pages should be followed or not. A very helpful gem to get your Ruby on Rails SaaS product more SEO friendly.

Adding SEO to your SaaS product isn’t difficult to do, and these gems provide a good start to not only improving the search engine result ranking of your SaaS product, but also improving the amount of traffic you get through easy to read URLs and better landing page titles. More traffic means more paying customers.

SEO 101 for SaaS Product Owners

As a SaaS product owner, you want your product to be known. You can run email campaigns, advertise and make yourself known on social media. When it comes to word of mouth, though, the search engine can become your greatest ally. You want your product to feature as high as possible in the search engine result pages. To do this we need to employ some search engine optimisation.

Search engine optimisation isn’t difficult to do, but it’s not something that can be applied as a quick fix. It takes time.

For your SaaS product, the landing page is everything. It’s the first port of call for potential customers, and it’s the first time they get to see your product. In this post we’re going to cover the essentials of search engine optimisation for your SaaS product landing page.

Use a title that focuses on the product name

The title tag is the section of your web page that includes the title of the current page. It’s used in search engine listings and sometimes in your browser. Page titles are important in search engine ranking algorithms.

The title tag itself should be placed in the <head> section of your page. It looks something like this:

<title>ACME Landing Tools</title>

For your landing page, create a title that focuses on your product name and uses keywords relevant to your product. Keep the title short so that it can be displayed in search engine results and in browser window titles. The longer the title, the greater the chance that a search engine will cut your title down.

Add a product description

The meta description tag is a brief description of the current page. It looks like this in your web page:

<head>
    <meta name="description" content="Here's a description of the current page"
</head>

Meta description tags are not important in search engine rankings, but where they do become important is in the search engine result pages. The meta name description is used in these listings to describe your page.

For your product landing page, this is a chance to get someone to click through to your product from the search engine results pages. Write the meta description to appeal to humans. It’s not going to improve your search engine listing directly, but the more people that click through and use your product, the better the chance those users will share the benefits of your product and its link in other places on the Internet.

Be mobile friendly

Mobile searches have taken over from desktop searches in the last couple of years for Google. It’s safe to say that other search providers will see a similar trend in their search analysis. What does this mean for your product?

Whether your product landing page is rendered on a desktop, a tablet or a mobile, you should ensure that it can display the product’s primary content on all of these devices.

Search engine optimisation can be done across a number of pages or indeed across all of the pages in your product. No other page is as important as your product’s landing page, and that’s where you should begin your search engine optimisation work.

While it may take some time, seeing your product among the top search engine results for your market will attract more people to your product landing page. With great copy and imagery on this landing page, you should be able to convert a number of these visitors to paying customers.

SEO and Why it Matters for SaaS Products

Is your SaaS product flagging in search engine listings? Are you worried that your application isn’t being found on the first page of results on the big search engines?

Getting your product to the top of the search engine results isn’t a key requirement to a successfully marketed product, but ranking is good practice to make your product easier to find if you want to attract as many customers as possible. This process of promoting your product in search engine results is called search engine optimisation or SEO for short.

This month I’m going to delve into the realm of search engine optimisation and how it relates to web applications. By the end the of this series, I promise you’ll be much clearer on search engine optimisation, and you’ll be able to improve the rankings of your web application.

So what is SEO?

To put it simply, search engine optimisation is the process of making changes to your website that make it more appealing to search engines. The more appealing the website, the higher the search engine will place your website in its search rankings.

Search engines use crawlers to traverse your website and validate the HTML that makes up your web pages, also noting hyperlinks to your website found on other sites. They use this information and other algorithms to determine how relevant a website is when it is searched for using keywords.

I don’t need to tell you as a product owner why this is important.

When it comes to marketing your product, you can find customers from different marketing campaigns across email, social media and advertising, but when it comes to word of mouth many people will search for your product, and that’s where search engine optimisation is important.

The higher your product is placed in the search engine listings, the quicker it will be for people to find it.

There are a number of things to consider before you begin optimising your product for search engine optimisation.

It takes time

Don’t expect your product to be sitting in the top spot of the search results for your market after a couple of days. SEO isn’t a recipe for overnight success. It’s a culmination of a number of small changes to your website that result in search engines gradually increasing your ranking if they find your website adheres to their ranking algorithms. This takes time, though, and should be viewed as a long-term project. It’s like building the online reputation for your product. It’s going to take a bit of time while word gets around.

There’s more than one search engine

Your SEO goals shouldn’t be tailored to one individual search engine. Yes, Google are the granddaddy of search engines, but they’re not the only search engine out there. While it’s great that you want your site to be on the first page of Google, you should also consider checking other search engines that are popular and relevant to your product.

Over the next few weeks we’re going to look at the different components of a webpage that affect how search engines index your product and where it will appear on those search engine results pages. Then we’ll look at a number of tools you can use to identify areas where you can improve your product’s SEO, as well as some libraries that will help in your web application.

Finally, we’ll build a sitemap for a Ruby on Rails application and allow it to be submitted to a number of search engines.

Search engine optimisation is often seen as a a bit of a black art, but with a little knowledge and some careful tweaks you’ll have your product set up so that it can be indexed by the search engines and displayed higher up in their search engine result pages.

The RSpec Refresher

I generally use Minitest for testing when I do client work, but recently I’ve been working on a project that uses RSpec as the main testing library. Now, to say that my RSpec is rusty would be an understatement, but after a few days it seems that it isn’t much different from the spec version of Minitest.

For this post we’ll take a look at an example of an RSpec spec and all the different parts of it, as a way of familiarizing ourselves with how it works.

Let’s look at a spec for our Ruby on Rails application, which has a resource for accounts.

Describing

We begin with the describe method. This is one of the most common methods you’ll use in RSpec. The describe method signifies the start of an example group. An example in RSpec is a test, so our describe method is indicating that this is the beginning of a group of tests.

describe 'Accounts' do
  describe 'GET index' do
  end
end

In this case we have a top level describe block for the Accounts resource with a second nested describe block for the index action of our accounts controller.

Contexts

Contexts are much like describe blocks. They allow you to organise your specs so that they are more readable. They can also be helpful to signify we’re running the test under certain criteria, like whether we’re logged in or out. Let’s take a look at our accounts spec and add some context to it.

describe 'Accounts' do
  describe 'GET index' do
    context 'when logged in' do
    end

    context 'when logged out' do
    end
  end
end

We have added two new context blocks that show for the first test we are logged in and then for the second test show that we are logged out.

The Spec

Finally, there’s the example itself, the code that we run to assert that our code behaves as intended. To do this we use the it method to define our example. It should look something like this:

it 'shows all accounts' do
end

Next we want to ensure that the page responds as expected. We’ll use an assertion for this:

it 'shows all accounts` do
  get accounts_path
    
  expect(response).to render_template(:index)
end

There are a few things going on here, so let’s look at them one line at a time. First, there’s the command to get the accounts path. For our controller spec this could be a get, post, put or destroy.

This sets up our example with something to test. In this case we’re testing the response from getting the index action for the accounts resource.

Next, there’s the assertion itself.

expect(response).to render_template(:index)

Let’s start with the expect method. This is the new syntax for RSpec and it’s recommended to be used on all new projects you use RSpec for.

Previous versions of RSpec would have had an example like this:

response.should render_template(:index)

The expect method takes an argument that could be any Ruby object. The assertion comes from the to method that is called from the Ruby object we’ve passed through to response.

In this case we’re asserting that the response will render the index template.

We should also add a few assertions for any expected accounts we should see and what should happen if we try to access the accounts page when we’re not logged in. Let’s add those in to see our final spec.

describe 'Accounts' do
  describe 'GET index' do
    context 'when logged in' do
      it 'shows all accounts' do
        get accounts_path
    
        expect(response).to render_template(:index)
        expect(response.body).to match /ACC0001/
        expect(response.body).to match /ACC0002/
      end
    end
		
    context 'when logged out' do
      it 'redirects to the login page' do
        get accounts_path
			
        expect(response).to redirect_to(accounts_path)
      end
    end
  end
end

So what we have now is a set of tests for our accounts index action. It’s simple and there are areas where we could improve our specs, but let’s save that for another day.

Taking the above spec, it’s easy to see the final description for each example by concatenating the arguments passed into each describe, context and it method.

Accounts GET index when logged in shows the accounts
Accounts GET index when logged out redirects to the login page

In other words, we expect the accounts GET index action to show a list of accounts when we’re logged in, and we expect the GET index action to redirect to the login page when we’re not logged in.

With the use of describe, context and it we have a readable spec the describes the expected behaviour accurately.

Just A Different Syntax

RSpec isn’t that much different from any other test framework out there once you get to the essential parts you need for your test. RSpec just has a different syntax.

My return to RSpec has meant learning its new syntax, but I am finding that the new syntax is winning me over and I’m wondering if I should use RSpec for future client work.

Look out for the follow up post to this one in the next couple of weeks as we look at reusing code in our specs and a few other goodies I’ve picked up from using RSpec again.

Why You Should Choose Ruby on Rails for Your Next Product

Maybe the hype of Ruby on Rails is decreasing, but that doesn’t mean the framework isn’t worth considering for your next project.

What follows is a few reasons why you should consider using the Ruby on Rails framework for your next product.

You want to market your product quickly

In the early days of any product, it is important to test the initial idea. Prototyping your idea can be done in a number of ways, but with Ruby on Rails your prototype can take the form of just a basic application that can then be grown into a more mature product.

Many prototypes for applications might look nothing like what the product can become, but with Ruby on Rails you can go from prototype to first version of your product without changing the underlying technology.

Once you’re at the stage of shipping a product, the momentum doesn’t need to slow down. Speed is everything when you’re building a product. It’s not so important to deliver a complete product, but it is important to continually deliver features, improvements and fixes for your product.

Ruby on Rails is a productive web framework that allows the building and shipping of features quickly. Even though Ruby on Rails is opinionated in how your application should work, it is a web application framework and therefore suited to building most types of web sites, web applications and application platform interfaces. As long as you’re working within these boundaries, your development team should have no problems in frequently shipping features, improvements and changes for your application once it leaves the prototype stage.

You want your product to be stable

Ruby on Rails is a stable framework with a tested history of success. Basecamp, Highrise, Github and Intercom are all examples of Ruby on Rails in production environments, websites that are proven success stories and scale to thousands of users.

Alongside Ruby on Rails’ proven track record is that it is actively maintained by hundreds of developers who devote their time to making Ruby on Rails what it is today.

Sure, Rails isn’t the new hotness, but you don’t want an untested platform running an important part of your business. You want a stable and dependable framework. And that’s exactly what Ruby on Rails is.

You want your product to be within budget

Ruby on Rails is open source and free. There’s no licensing costs and no subscription fee. You can download the framework and build your own product for free.

Not only is the framework free, but Ruby on Rails freelancers and developers are competitively priced. Whether you’re building a prototype or looking to migrate an old Ruby on Rails legacy application, there’s a developer out there for your needs.

Lastly, Ruby on Rails has a number of hosting options available. For a couple of cups of coffee a month, you could have your product running on Heroku for the initial launch. If your needs are a little bit more technical, you can hire an engineer or two to build a custom hosting solution using Amazon Web Services.

Need More Reasons to Choose Rails?

The most important reason to choose Ruby on Rails is that it is a stable framework and less prone to change in the next few years. The web development landscape is always changing. New technologies and frameworks make their entrance proclaiming to be new and improved, but the real power of any framework is its history. And for Ruby on Rails that is a long time.

If you’re interested in building a prototype of a product for your business, I would love to hear from you. Get in touch here.

What You Should Know if You're Using Microsoft SQL Server with Ruby on Rails

Microsoft SQL Server isn’t usually the first choice when it comes to choosing a database to persist data for your Ruby on Rails application.

Traditionally, developers opt for PostgreSQL, MySQL or even SQLite. These databases are available on different platforms and are free to use. This year’s Ruby on Rails hosting survey by Planet Argon found that 60% of developers choose PostgreSQL for their application when it is deployed to production.

If you look past the Windows platform dependence for Microsoft SQL Server, you’ll find that it’s just as capable for persisting data as any of the databases mentioned above. You just need to know a few things before you begin.

Start with the SQL Server Adapter gem

The ActiveRecord SQL Server Adapter is the gem to use if you want to make full use of Microsoft SQL Server. Not only does the gem make connecting to SQL Server easier, it allows you to execute stored procedures and provides native data type support for your Rails application.

Custom Tables and Primary Keys

Rails creates tables and primary keys through migrations. These migrations assume a naming pattern for tables and primary key fields. This isn’t always the case with SQL Server though.

I’ve worked with a number of different SQL Server databases in the past. From retail sales reporting to ERP platforms, I’ve seen SQL Server used in different domains by different IT teams. One thing that sticks out from these experiences is that the conventions used in SQL Server can vary from one team to the next.

This isn’t a big problem, though, as Rails allows the use of custom table names and primary keys, so you can pair any table with its respective model.

class Widget < ActiveRecord::Base
  self.table_name = CompanyWidgets
  self.primary_key = CompanyWidgetID
end

Views are Table

A lot of SQL Server databases use views to provide a customised view of data. These views are a great way of building aggregated listings of data, which means less work to do for Rails. How do we handle these views in Rails, though?

Simple. Rails can interpret views as tables.

class SupplierWidget < ActiveRecord::Base
  self.table_name = vw_SupplierWidgets
  self.primary_key = SupplierWidgetID
end

By creating a new model, assigning it the view name as the table name, and giving it a primary key, we can then use the view as a table. Bear in mind that this view is read-only and can only read records from the database. Therefore, ActiveRecord methods such as update and destroy won’t work.

Stored Procedures

Stored procedures are a common part of Microsoft SQL Server databases. Whether you agree with the notion of reusing SQL code to handle the data manipulation operations for the database, there’s a good chance there will be a case where a stored procedure will need to be called from your Ruby on Rails application.

Through the use of the ActiveRecord SQL Server Adapter you can execute a stored procedure with parameters from your Rails application.

ActiveRecord::Base.execute_procedure :process_widgets, zone: EU-011

Microsoft SQL Server isn’t the first choice of database when it comes to Ruby on Rails. It certainly wouldn’t be my first choice database for a Rails application. However, the constraints of the project or the needs of the client can often outweigh your own preferences.

Whatever the case for using Microsoft SQL Server, it’s just as a capable as any other RDBMS out there. With some basic knowledge about the structure of Microsoft SQL Server you’ll be able to develop Rails apps just as effectively as if you are using PostgreSQL or MySQL.