Saturday, 27 December 2014

API Development in Ruby On Rails, Entities

In my last blog post I presented in general the features I like the most about the grape gem. Now I will present the grape entities which are related to the presentation of the returned data. I like these entities a lot because they are an OO way to present data and they help a lot to keep my presentation layer DRY.

The last statement of every grape call is returned to the caller as JSON.
Despite this simple efficiency I like to have more control over the returned data and I use the grape entities to format the returned data wherever I can. I can also rspec them and I am doing it extensively because I am a Test Driven Guy ;)

Let me present some examples of entities their usage and how do I spec them:

Here is the spec for the entity:

describe GameEntity do
  describe 'fields' do
    subject(:subject) { GameEntity }
    it { is_expected.to represent(:id) }
    it { is_expected.to represent(:user_id).as(:owner_id) }
...


Here is the entity itself:

class GameEntity < Grape::Entity
  expose :id
  expose :user_id, as: :owner_id
...

The part of the grape API:

  namespace :games do
    desc "Retrieve all the games"
    params do
      optional :include_reviews, type: Boolean, default: true, desc: 'Accepts: true/false.'
    end
    get do
      games = Game.actual.limit(500)
      present games, with: GameEntity

This was simple so far. But I can use a more sophisticated GameEntity in case I want to present the included reviews. In all other cases I will use my old simple GameEntity to present the Game.

Let's see that case too:

I modify the grape API to this:

    ...
    if params[:include_reviews]
      games = games.includes(:reviews)
      present games, with: DetailedGameEntity
    else
      present games, with: GameEntity
    end

I also spec the new entity:

describe DetailedGameEntity do
  describe 'special fields' do
      subject(:detailed_game) { DetailedGameEntity(game).as_json }
      specify { expect(detailed_game[:reviews]).to be_an(Array) }
  end

Of course the above was a very simple example.

In real world scenarios we can find ourselves that we are reusing the entities like this:

class DetailedGameEntity < Grape::Entity
  expose :game, using: GameEntity do |game, options|
    game
  end

  expose :venue, using: VenueEntity do |game, options|
    game.the_venue
  end

  expose :visitor_team, using: TeamEntity do |game, options|
    game.visitor_team
  end

  expose :host_team, using: TeamEntity do |game, options|
    game.host_team
  end
end

As you can see we are keeping our entity codebase DRY by calling the TeamEntity twice in the DetailedGameEntity. This is a typical use of delegation of the Entities.

Let me show a more complex example of our entities:

The usage of the entities:

  desc "Retrieve all the reviews belonging to a team"
    get do
      ...
      present reviews, :with => ReviewPresenter, user: current_user
    end

The entity itself:
  class ReviewPresenter < Grape::Entity
    expose :current_user_likes do |review, options|
      review.likes.pluck(:user_id).include? options[:user].id if options[:user].present?
    end
  end

And finally the spec for the entity:
describe ReviewPresenter do
  describe 'special fields' do
    context 'without passing a user' do
      subject(:presented_review) { ReviewPresenter.new(image.review).as_json }
      specify { expect(presented_review[:current_user_likes]).to be_nil }
    end

    subject(:presented_review) { ReviewPresenter.new(image.review, user: current_user).as_json }
    ...
      context 'user is the current_user' do
        specify { expect(presented_review[:current_user_likes]).to eq(true) }
      end
    end
    ...
  end
end

What I was doing here is to populate the field 'current_user_likes'
 to true or false depending if the current_user likes or not the presented review.

As you can see the presentation layer of any grape API could became more DRY and versatile by using the grape entities.

Enjoy using them ;)

Friday, 26 December 2014

API Development in Ruby On Rails

I met a technology and a set of gems which were designed to develop any API in Ruby On Rails about half years ago.

The set of gems were:


At first glance it seemed that it adds complexity to the Rails application compared to standard Rails JSON returns. After I played a bit with it I suddenly realized that its API formulating DSL is much more superior. So I started to like it :)

Let me list the elements of DSL I like most:

  • ability to mount API endpoints. This can be very handy if I want to unmount certain unused parts of the API.

      mount Caesars::Ping
      mount Caesars::PingProtected

  • ability to describe the API endpoint. This description will appear in the Swagger documentation. It is a help for the API user.
  • ability to specify the parameters (type, mandatory or required).
      params do
        optional :user_ids, desc: "JSON array of the user ids to be deleted."
        requires :group_id, type: Integer, desc: "The id of the group"
      end

By specifying the type our parameters will be converted automagically to the specified type. It is easier this way for us developers to write our core logic.
  • a complex DSL to organize the API hierarchy and use route params. I consider this the most powerful feature. I can easily organize the API to look more like Facebook graph API or Philips Hue API than standard Rails restfull API.
      namespace :teams do
        route_param :id do
          desc 'Retrieve all games belonging to teams'
          get 'scores' do
            #DO logic here
          end
        end
      end

The grape features are many more including versioning. Take a look for a complete description at grape site ;)

Thursday, 25 December 2014

Hi,

I have news for you. My daughter had been born in august :) With Her time passed very fast.
I even missed the new macbook release date which was in July. But I don't feel disappointed because according to the rumors the newer MacBook will have a much better CPU. So I will wait for the next generation of MacBook pro :)

Here is a picture about us:


Monday, 1 April 2013

Editing the code with the speed of thought

Hi

I changed my code editor from Textmate2 to Sublime. A friend of mine told me about it and I was so curious that I needed to try it. I started to love it right in the first moment mainly because of the existence of the command palette and its modular feature approach and the multiple editing feature.

The command palette was for me like some sort of help combined with a quicksearch-autosuggest menu. When I thought to something I would do I typed in and if I had luck then the feature was already there. If not then I needed to search for a suitable package which did the desired functionality.
I saw a huge potential in this approach because I always wanted to edit my code like the code editor would be a extension of my body. In other words I wanted to edit code with the speed of my thought.
By default the desired functions were not there. I needed to search for some packages and even edit those packages to achieve my desires. I wanted to toggle between quote types 'a', "a". I wanted to convert a string to a symbol and vice versa "a", :a. I wanted to toggle the do end blocks with the braces blocks. I wanted to convert amongst sneak_case, pascalCase, dash-case, dot.case, slash/separated

So by using it continouosly for more than half year I installed these packages:

          For converting each other from any of them:
    • "sneak_case"
    • "pascalCase"
    • "dash-case"
    • "dot.case"
    • "slash/separated"
  • Clipboard History - for using multiple history feature
  • CoffeeScript - syntax for coffee script
  • Cucumber -  syntax for cucumber
  • Eco - syntax for eco template
  • ERB Insert And Toggle Command
          For toggling amongs these
    • <%= %> 
    • <%-  -%>
    • <%  %>
    • <%=  -%>
    • <%#  %>
  • Gist - I like to store my snippets on gist and access them from sublime
  • Missing Palette Commands
  • Plain Tasks - For storing my tasks in plain text format but nicely formated, like the below list
    • ✔ task 1 @done (13-04-01 21:28)
    •  ☐ implement sorting
  • RSpec - syntax for my specs. I am a TDD advocate. It saves me a lot of time.
  • Ruby Block Converter - for toggling amongst {} block and do end blocks.
  • SFTP - for editing remote files.
  • Toggle Symbol To String for toggling between "symbol"and :symbol
  • Toggle Quotes for toggling between 'string' and "string"
  • Advanced New File for creating deeple nested directories when I place a file into them.
  • Nettuts + Fetch for fetching the latest jquery.js or jquery-ui.js or backbone.js libraries.

Often the commands were missing from some of these packages. So when I searched for 'toggle block' then no result was shown however I wanted to convert a block from "{}" style to "do end" style. This was a bottleneck in my speedy coding... In these cases I needed to open the package add the command to the Default.sublime-commands file and then make a pull request. This way if I eventually forgot the key combination of a feature I could search for it in a command palette.

May I ask any developer who makes a sublime package to add this file to the package and enlist the commands there.
There is the multiple editing feature I like the most... :)
And it is a very fast editor.
I also like the snippet feature of it.

Overall all I can say s that it is a very handy code editor and it worth the money for buying it and spending time to learn it ;)