2015-03-06



Last week, I talked about my experiences using DoneDone to manage household issues. To accompany my post, I wrote a simple Rails application to query data from the DoneDone API and display it on a publicly-accessible dashboard. Today, I’d like to walk through the process of building that application from the ground up.

If you’d like to see the end result, you can see the source code on GitHub. Otherwise, follow along to recreate the demo step-by-step.

Setting up your environment

First, make sure you have Ruby, RubyGems, and Rails installed. You might be interested in using RailsInstaller or RVM to simplify this process on your system.

For this demo, I’m using Ruby 2.1.1 and Rails 4.2.0.

Creating a new Rails project

Using your Terminal or Command Prompt, navigate to the directory where you’d like to store your project, then run:

Here, we’re indicating that we don’t want Rails to install a test framework inside our app with the -T modifier. This is simply to keep our directory a bit cleaner, as we won’t be writing tests for this short demo.

Next, switch into your new donedone-public-dashboard directory for the remainder of the demo.

Creating models

Although we’ll be retrieving all of our data from the DoneDone API, we don’t want to do this every time a user visits our dashboard. Instead, we want to download all our data from DoneDone behind the scenes and store it in our local database. Our application will then display the local data, saving us from making unnecessary requests from DoneDone.

But first, we’ll need to create models to hold all this data. Our models will closely follow the structure of the data that’s returned by the DoneDone API methods. Enter this in your console:

This command creates a database table named projects with two columns: project_id (which stores integers) and title (which stores strings). This also creates an ActiveRecord class named Project, which you can find in /app/models/project.rb. This class allows you to interact with the database records very easily using Ruby code.

Note: Why didn’t we simply call the first column id? Well, Rails automatically gives every database table a column named id, which it uses to internally lookup records. But, since the projects we retrieve from DoneDone will have their own ID values, we need another column to keep track of these. You can think of the id column as the local ID, and the project_id column as the DoneDone ID.

Now let’s create a model to store issues:

Here, we’ve used a few shortcuts to make the command less wordy. The generate keyword can be shortened to g, and any columns that don’t specify a data type will automatically be created as string types.

Notice that the project column uses a references type – this will create a foreign key relationship between projects (the parent table) and issues (the child table).

Finally, let’s generate a model definition for issue history data, so we can view how each issue has changed over time.

To recap, each Project can have multiple Issues, and each Issue can have multiple Histories.

Now that we’ve finished our model generation, we need to actually create these tables in our database. Each time we’ve used the rails generate model command, Rails has created a small piece of database migration code, which you can view in the /db/migrate directory. We need to run all these migration methods to synchronize our schema to our database:

Improving relationships

Now that our models have been created (both in code and in our database), we need to give Rails a bit more information about how our models are related to each other.

We used the references data type to indicate that some of our models are related to others. But, we need to specify exactly how these relationships should be enforced. Open /app/models/issue.rb and you’ll see this:

The belongs_to line indicates that each Issue record belongs to a Project record. But we still need to tell Rails that each Issue can have its own History records. Change your model declaration to look like this:

Now Rails knows each Issue belongs to a Project, but can also have many History items.

Update the remaining models with their appropriate relationships:

/app/models/history.rb:

/app/models/project.rb:

Connecting to the DoneDone API

Now that our models and relationships are ready, we can retrieve remote data from DoneDone and populate our local database. To get our data, we’ll be using a Ruby gem called Faraday.

Open /Gemfile and add the following line to the bottom of the file:

Save your Gemfile, then return to your console window and run this command:

This will download the faraday gem and install it for use with your app. Faraday gives you an easy way to interact with remote APIs, just like DoneDone’s REST API.

Next, we need to define a Ruby class that will retrieve data from the DoneDone API and store it in our local database. Create a new file named /app/services/done_done_api.rb. Place the following code in the new file:

This code may look a bit overwhelming, so let’s step through what each method does:

The self.conn method creates a new Faraday connection, using the URL of your DoneDone account. It also uses your DoneDone username and API token to authenticate each request. Replace the placeholders here with your appropriate DoneDone values. Tip: Use ENV variables to store this data on a production environment.

The self.sync_projects and self.sync_issues methods simply use our connection function to request a URL, parse the data that’s returned, and insert or update the data in our local database. self.sync_issues also uses a few private methods (defined at the bottom of the class) to loop through issues and their histories.

Since our service class lives in the /app folder, we can use it anywhere in our application’s codebase. So, let’s make it easy to execute our API functions directly from our model objects.

In /app/models/project.rb, add the following method just above the last end keyword:

Now we can call Project.sync_from_api from anywhere in our application, and Rails will use our service method to connect to the API, download data, and populate our database. Easy! Let’s do the same for Issues. In /app/models/issue.rb, add the following method just above the last end keyword:

Now we can call Issue.sync_from_api to synchronize our issues.

Adding controllers and views

We’ve spent some time creating our back-end logic, but we still have no way to actually view any data in our app. Let’s add some controllers and views so we can actually see our data.

Back in your console, run this command:

This creates a controller named issues_controller, which has two action methods: index and show. When a user visits our index URL, they’ll see a list of all our issues. When a user clicks on a specific issue, they’ll view its detail via the show URL.

Since the controller actions are responsible for preparing data for display to the user, let’s update these methods in preparation for our views:

/controllers/issues_controller.rb:

The index method simply returns all Issues in our database, ordered by their last_updated_on date. The show method looks up a specific issue specified by the :id parameter (which will be part of the URL), and also retrieves its history data.

Each controller action also created its own view – this is where we’ll write HTML to display our data. Let’s update these:

/app/views/issues/index.html.erb:

/app/views/issues/show.html.erb:

Finally, let’s make our view look a bit nicer by including the Bootstrap CSS framework. Add the following to the bottom of /Gemfile:

Then run bundle install. Next, open /app/views/layouts/application.html.erb and replace the <%= yield %> line with the following:

Next, add the following CSS content (you’ll need to create the first file):

/app/assets/stylesheets/bootstrap_and_overrides.css:

/app/assets/stylesheets/issues.scss:

This will give all our content a nice, simple layout.

Let’s also generate a quick URL for manually synchronizing our issues. We’ll then be able to visit this URL anytime we want to refresh data from the API:

And in /app/controllers/sync_controller:

This performs our sync functions, then redirects to the application root URL. Speaking of which, let’s update our routes so that the root URL simply displays the list of issues. Open /config/routes.rb and update it to this:

This sets our Issue list view as the root URL. Finally, we’re ready to go! In your console, run the following:

This will start a local web server at http://localhost:3000 – open that up in your web browser.

You’ll see an empty page, but that’s OK! We haven’t synchronized our data from the API yet. Just go to http://localhost:3000/sync to populate your local data. Now you should see all your issues!

Note: In a production environment, we would typically create a recurring task to call the sync methods every few minutes, instead of triggering them manually.

Wrapping up

While this demo has covered quite a bit of ground, it’s only meant to serve as a quick introduction to querying RESTful APIs with Rails. If you’d like to learn more, be sure to check out the following links:

donedone-public-dashboard source code on GitHub

DoneDone API

Ruby on Rails

The Ruby on Rails Tutorial

Faraday gem

The post Building a Rails dashboard app with the DoneDone API appeared first on DoneDone.

Show more