A complete guide for building microservices with Ruby on Rails – Part I

As a Ruby on Rails developer I have built numerous API applications, I thought it will be a good idea to write a series of posts about building API application with Ruby on Rails.

Before you start the reading, please refer to this sample API application which has following technology stack.

Rails v5.2.0 
Ruby v2.4.0
MongoDB v3.4.2

In this series of posts I will cover following about API’s

  • Introduction to API’s, difference between normal and API only Rails application.
  • Versioning
  • Authentication
  • Throttling
  • Documentation and Testing

Brief about API’s

What are API’s?

API’s are nothing but Application Program Interface with set of routines, protocols and tools used for building software application, where consumer requests to the provider with uniform interface and receives the response in requested representation like JSON, HTML etc.

A high level diagram:

Screen Shot 2018-04-27 at 6.20.47 PM

But many times you might have heard that the API’s are Restful.

What are Restful API’s?

Restfulness is derived from Representational State Transfer design idiom for web services that embraces a stateless client-server architecture, having a resource that can be Created, Read, Updated or Deleted (CRUD operations). This resource with a URI(Uniform Resource Identifier) is transferred over a Uniform Interface like HTTP with representation (HTML or JSON or XML) whose state keeps on changing.    

Not understood?

Lets see how to build API’s with Rails

There are various options for building API’s, traditionally many developers were using gems like grape, rocket_pants or rails with name-spaced controllers and routes but building API’s with grape and rocket_pants gems is a tedious job as these gems have their own DSL.

If you choose rails with custom configurations for API’s, it will ease your job upto certain extent but rails is not built for API’s, As rails carries some unnecessary modules and middleware(s) alongside which are useless for api only application, then what to use? Well a better option which is developed for building api only applications is rails-api gem.

What is rails-api and How its different from Rails?

Rails-api – Rails for API only applications, in simple terms

  • Rails API = Rails – Middleware(s)
  • Without assets, views and helpers and much more…

You can create API only application after install latest stable rails version with following command

$rails new expense_manager --api
If you notice the option --api in above command, this is the option which is responsible for generating API only application with following two noticeable differences from traditional rails application.

1. A closer look at ApplicationController

In normal rails application, ApplicationController looks like

  class ApplicationController < ActionController::Base
    ...
  end
In rails api only application, ApplicationController inherits from ActionController::API
  class ApplicationController < ActionController::API
    ...
  end
Inheriting ApplicationController from ActionController::API has removed extra controller modules which are not necessary for API only applications, to check which all modules it has neglected compare the output of following commands.
  ActionController::API.ancestors - ActionController::Metal.ancestors
  ActionController::Base.ancestors - ActionController::Metal.ancestors

To name a few modules it has removed controller modules like ActionView::Layouts, ActionView::Rendering, ActionController::Helpers, ActionController::FormBuilder, ActionController::Flash, ActionController::Cookies etc.

2.  Handled set of middleware

In config/application.rb you can see the line

config.api_only = true

This line is responsible for removing middlewares that are not necessary for API only applications.

If you run

 $rails middleware 

in normal rails application you will see the following list of middlewares.

api_only_false

And in API only rails application middleware list looks like

api_only_true

From above lists of middlewares its clear that in API only application middlewares related to cache, cookies, session, flash etc. are removed making API application lighter and more suitable for API’s.

We have covered API introduction and key differences between normal and API only rails application. In the next post we will see how to structure and version your API’s, stay tuned.

Advertisements

10 Signs of a good Ruby on Rails Developer

I have been working as Ruby on Rails developer since last five years with Josh Software, I felt that I should write down my learnings about the best practices followed by the RoR developer. How I learned …? of course to learn something you need to commit the mistakes, thats how we learn right?

Let’s see, What all you should follow to be a ‘Good’ Ruby on Rails developer.

1. Your migrations are “thoughtful” …

Whenever you come across database table schema design do you think through all the aspects like

  • The table which is being designed where its going to be used? How much it might grow in terms of the data size? (Imagine the worst future of your design)
  • Have I kept correct data types, defaults, constraints if any? Most of the times we really don’t need integer columns, We can use smallint instead for smaller set of integers, similarly varchar(10) vs varchar(255) vs text.
  • Have I added indexes wherever necessary? Thinking through What kind of the queries this table is going to handle?

A special point…Do you write multiple migrations for same table? if yes, its a bad habit.

Often we don’t think through all the points mentioned above and end up creating multiple migrations for same table which causes codebase to look scary.

Instead you should use up and down on the migration to fix or alter the table, change in the requirement is an exception to this.

2. You always follow the single responsibility principle

We all know a convention of “skinny controller and fat model”, some of us already follow this but do we follow it wisely.

We are living in the Rails 5 era, so Why to overload models?

Why not to follow “keep everything skinny move extra fat to concerns or service objects from the models”, the classes in the codebase should be designed to handle single responsibility.

I came across the following posts about how to organise controllers and using service objects in Rails.

3. You write test cases to test the “code”

I have seen many applications whose CI builds takes ages to finish, What exactly they are testing?

Your test cases should be testing the “code” not the machine performance, better test suits

  • Share objects between different examples.
  • Uses method stubs and avoid the repetitive calls to the methods.
  • Don’t test same code twice, if you have sharable piece of code and used at multiple places then don’t write test cases in multiple places.
  • Does not creates unnecessary test records, unknowingly many developers end up creating unnecessary test records.

If your are using gems like fakerfactory_bot_rails and database_cleaner to create and clean test records then creating unnecessary records can cost you time and speed.

Simple example,

create_list(:user, 10)

Much better will be reduce the list size, if you are not doing anything special with 10 users.

create_list(:user, 2)

To know how to write better Rspec then this guide is for you.

4. You keep production environment healthy

If you are an engineer and reduce efforts of others, then you use the utilities of other engineers to reduce your efforts.

A healthy Rails production environment always have

  • Monit  – Is everything up and running? if not get notified.
  • logrotate – rotates, compresses, and mails system logs.
  • crontabs with whenever, schedules work for you.
  • Database backup scripts running in maintenance window.
  • Exception notifiers like Senty or Rollbar or ‘anything that suits you’.

5. You follow basic git etiquettes

If you are working in a team and using git then you follow the git etiquettes like

  • Don’t commit untracked files – we often keep git untracked files like ‘something.swp’, ‘backup.sql’, ‘schema.rb or structure.sql backups’, ‘some.test.script’, you should not commit such files.
  • Branch naming – naming something is always difficult but you have to do it, the feature branches should have sensible names, don’t use names like ‘something-wip’, ‘somthing-test’.
  • Delete the feature branches after merge – no explanation required.
  • Commit messages – your commit messages must have ‘Github issue number’ or ‘any project management story number/link’,  ‘brief description about feature/task’

6. You don’t ignore README.md

Remember you are not the only one who is going to work on particular application for your lifetime. Someone will takeover you and he should not waste his time in figuring out that how to setup things.

Your application repository must have updated README.md with detail steps about setting up a application for the first time.

7. Secrets are “really” secrets for you

We often use credentials for database configs, secrets.yml, third party api’s like AWS, payment gateway, sentry etc.

You should not commit such credentials/secrets/environment variables to the Github instead you keep them secure with gems like dotenv-rails, figaro or simple dot files that are not committed to the repository.

A sample file of such credentials should be committed and updated regularly.

8. You do code reviews and discuss feature with team

While working in a team you should get your feature reviewed from another team mate or before starting on any feature discuss it with the team thoroughly, advantages of the code reviews or feature discussion are you will come across many scenarios that are not thought of.

If you are the only one who is working on a application then you must criticise your own code and cover all the scenarios in test cases.   

9. You are up-to-date and keep updating

In open source community we get frequent updates or releases for ruby, rails and gems, you must keep yourself aware and informed by subscribing to the repositories or mailing lists and update your application libraries.

Also you should stay alert on security fixes about the production operating system, database so you can take necessary action on time.

10. Need not to say…

You write clean and maintainable code and your codebase is

Well there are many more points that can be included in this list but I feel these are the most important to fill in first into this list, If you find that I have missed anything more important then you can comment on this post.

Thanks for the reading upto here, hope this will help you to become a ‘Good’ developer.