Gem Grape 是否支持方法级别 定义返回数据的格式

magic · 2013年06月01日 · 最后由 Magic 回复于 2013年06月02日 · 4153 次阅读

最近在用 Grape 写个简单的微信机器人,测试的时候碰到一个问题:正常的微信接口查询是没问题(下面代码的 post 接口),但是微信校验接口总是不通过(下面代码的 get 接口);分析原因是微信接口查询默认返回的是 xml 格式,API 定义的默认返回格式也是 xml(format :xml)所以没问题,但是微信校验接口返回的是字符串,Grape 执行返回数据的 to_xml 方法时报错:cannot convert String to xml。

大家遇到 Grape API 返回不同格式时如何处理?我是想要是 Grape 只是方法级别定义返回数据格式就好了,但是查了 Grape 官方文档也看到类似的说明,Google 也没找到。


module Wechat
  class API < Grape::API

    version 'v1', :using => :path, :vendor => 'weixin'
    format :xml
    content_type :xml, "text/xml"

    helpers WechatHelper

    resource :weixin do

      desc 'check weixin sign'
      get do
        # 返回字符串
        check_sign(params)
      end

      desc 'weixin response'
      post do
        request_body = request.body.read
        status("200")

        # 返回xml对象
        get_weixin_response(request_body)
      end
    end
  end
end

to_xml 貌似是 active_support 给数组和 hash 扩展的方法,string 当然没有啦

问题解决了,默认设置 format :txt,之后在每个 API 返回的时候根据情况转换。比如上面的 get 方法,返回的是 string,所以不修改;post 方法会的是 xml 对象,返回结果显示 to_xml 下。

post do
        request_body = request.body.read
        status("200")

        # 返回xml对象
        get_weixin_response(request_body).to_xml
      end
需要 登录 后方可回复, 如果你还没有账号请 注册新账号