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
4

1 回答 1

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
于 2012-05-21T23:25:07.933 回答