2012-05-21 55 views
2

我有一點我想要美化的sinatra api。我的大多數路由都是簡單的數據庫操作,但有一些涉及在執行數據庫操作之前調用外部服務。在所有情況下,除了我如何響應服務響應,大部分代碼都是相同的。有沒有靈活的函數式編程方法?更好的紅寶石 - 可能不重複部分功能?

這裏的這些路線中的一個例子:

get '/update_x' do 
    validateParams(params,:x) 
    xid = params[:x] 
    xName = getNameFromId(xid) 

    if xName 
     # Make request to proxy service 
     rid = generateRandomHexNumber(16) # generate requestId 
     params['m'] = 'set' 
     params['rid'] = rid 

     json = "{}"  
     begin 
     response = @resource["/"+"?rid=#{rid}&id=#{xid}&json=#{json}"].get 
     status = response.code 
     body = response.body 

     parsed_json = JSON(body) 
     if parsed_json['response'] and parsed_json['response']['success'] and parsed_json['response']['success']=='false' 
      msg = {:success => "false", :response => "unknown error"} 
      if parsed_json['response']['response'] 
      msg = {:success => "false", :response => parsed_json['response']['response']} 
      end 
      content_type :json 
      msg.to_json 
     else 

     #### Here is stuff specific to this api call 

      updateDBHelper(xid,buildUpdateOptions(params)) 

      params['ss_status'] = status 
      content_type :json 
      params.to_json 

      #### End specific to api call 
     end 
     rescue Exception=>e 
     params['ss_status'] = status 
     params['exception'] = e 
     content_type :json 
     params.to_json 
     end 
    else 
     msg = {:success => "false", :response => "Not found"} 
     content_type :json 
     msg.to_json 
    end 
    end 

回答

3

一般來說,如果你有改變每一次那麼簡單的事情將接受與這些自定義塊的一些任意代碼的一般模式。

def make_api_request(some, params) 
    # do what you need to do 
    yield(variables, that, your_custom_code, needs) 
    # do some more, maybe cleanup 
end 

get '/some_route' do 
    make_api_request do |variables, that, your_custom_code, needs| 
    # do custom stuff here 
    end 
end