ruby - 更好的 ruby​​ - 可以不重复函数的某些部分吗?

标签 ruby functional-programming refactoring sinatra

我有一个小的 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

最佳答案

一般来说,如果您有一个带有一些每次都会更改的任意代码的通用模式,那么最简单的事情就是接受具有这些自定义的 block 。

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

关于ruby - 更好的 ruby​​ - 可以不重复函数的某些部分吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10692955/

相关文章:

scala - 返回会破坏引用透明度吗?

java - 具有两个输出的重构方法

c++ - 建议对以下形式的 if 语句进行重构?

c++ - 如何修复采用类成员相对顺序的奇怪 C++ 代码

refactoring - 如何使用重构浏览器添加实例变量?

ruby-on-rails - Stripe API key 缺少 Rails

JavaScript 执行 Ruby 脚本

Ruby:使用存储在 TPM 中的 key

list - 为什么 Haskell 允许 Shape 列表,但不允许 Square 或 Circle 或 Triangle 列表

ruby-on-rails - Heroku 推送被拒绝,未检测到 Cedar 支持的应用程序(不同问题)