RABL - rendering a collection as an object with IDs as keys

In Ruby on Rails 4, I am trying to create an API for my website and instead use an array like this:

[{id: 1, name: "John"}, {id: 2, name: "Foo"}, {id: 3, name: "Bar"}]

      

I want to do it like this, because it makes it easier to search in javascript (and for other reasons):

{"1": {id: 1, name: "John"}, "2": {id: 2, name: "Foo"}, "3": {id: 3, name: "Bar"}}

      

It works:

# users/index.rabl

@users.each do |user|
  node(users.id.to_s) do
    partial('api/v1/users/show', object: user)
  end
end

      

But in a partial way, I want a different set of items (which are owned by the user) and I cannot get this to work. Is there a more elegant way to do this?

+3


source to share


1 answer


To select a hashmap over an array is definitely the best option if you have control over the underlying API code. From BigO notation, searching for hashes happens with constant time O (1), not O (n) as for an array.

Finding a key first from a database is the most efficient way to query data. The primary key is usually short and is always indexed. Use pagination for large datasets.

Let's assume there is no RABL (you can always create pure Ruby classes in RABL DSL code), but just an array:

array = [{id: 1, name: "John"}, {id: 2, name: "Foo"}, {id: 3, name: "Bar"}]
hash  = {}
array.each{ |elem,i| hash[elem[:id].to_s] = elem }

# {"1"=>{:id=>1, :name=>"John"}, "2"=>{:id=>2, :name=>"Foo"}, "3"=>{:id=>3, :name=>"Bar"}}

      



To pass the Ruby hash to Javascript on the client, you probably want to code it appropriately:

# hash.to_json
# {"1":{"id":1,"name":"John"},"2":{"id":2,"name":"Foo"},"3":{"id":3,"name":"Bar"}}

      

From Javascript, you request a hash by its key:

hash = {"1":{"id":1,"name":"John"},"2":{"id":2,"name":"Foo"},"3":{"id":3,"name":"Bar"}}
hash[1]
# Object { id=1,  name="John"}

      

0


source







All Articles