2017-07-18 98 views
0

我怎樣才能強制我的葡萄實體總是返回一個數組(集合),即使它只是一個單一的對象?我聽說有些人創建了一個在端點內部被調用的幫助方法,但我還沒有找到任何人在線做這樣的例子。強制葡萄實體總是返回一個數組?

實體的默認功能是,如果只返回單個文檔(mongoid對象),它將返回一個對象。如果返回一組文檔,那麼它將返回一個數組,我不希望我的客戶端應用程序每次都必須執行檢查,以查看是否從我的API返回了對象或數組。

## Resource (HTTP Endpoint) 
desc 'List departments a user can and cannot access' 
params do 
    requires :user_id 
end 
get :department_access do 
    @user = BACKBONE::User.find(@access_key.user_id) 
    requires_admin! 
    user = BACKBONE::User.find(params[:user_id]) 
    can_access = BACKBONE::Department.user_can_access(user) 
    no_access = BACKBONE::Department.user_cannot_access(user) 
    present_success can_access 
    present :can_access, can_access, with: BACKBONE::Entities::DepartmentBase 
    present :no_access, no_access, with: BACKBONE::Entities::DepartmentBase 
end 

-

## Entity 
module BACKBONE 
    module Entities 
    class DepartmentBase < BACKBONE::Entities::Mongoid 
     expose :name 
     expose :prefix 
     with_options(format_with: :mongo_id) do 
     expose :company_id 
     end 
    end 
    end 
end 

JSON響應

{ 
    "status": "success", 
    "request_time": 0.009812, 
    "records": 1, 
    "can_access": { 
     "id": "59699d1a78cee4f8d07528fc", 
     "created_at": "2017-07-14T21:42:02.666-07:00", 
     "updated_at": "2017-07-14T21:42:02.666-07:00", 
     "name": "Tenant Improvement", 
     "prefix": "CACC", 
     "company_id": "596927fb670f6eec21c4f409" 
    }, 
    "no_access": { 
     "id": "59699cca78cee4f8d07528fb", 
     "created_at": "2017-07-14T21:40:42.005-07:00", 
     "updated_at": "2017-07-14T21:40:42.005-07:00", 
     "name": "Field Operations", 
     "prefix": "CACC", 
     "company_id": "596927fb670f6eec21c4f409" 
    } 
} 

回答

0

一個同事和我想出了一個輔助的解決方案,創建一個總是返回數組一個輔助方法:

def present_array(key, data, entity) 
    d = (data.class.respond_to? :count) ? [data] : data 
    d = [] if d.nil? 
    present key, d, entity 
end