为 ActiveResource 中的每个请求添加 api 密钥 [英] Add api key to every request in ActiveResource

查看:47
本文介绍了为 ActiveResource 中的每个请求添加 api 密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个 RESTful Rails 应用程序,我正在尝试相互交流.两者都是用 Rails 3(目前是 beta3)编写的.对服务的请求将需要使用 api 密钥,这只是每个请求都需要的参数.我似乎找不到有关如何执行此操作的任何信息.

I have 2 RESTful Rails apps I'm trying to make talk to each other. Both are written in Rails 3 (beta3 at the moment). The requests to the service will require the use an api key which is just a param that needs to be on every request. I can't seem to find any information on how to do this.

您通过 site= 方法定义资源连接到的 url.应该有一个等效的 query_params= 方法或类似的方法.

You define the url the resource connects to via the site= method. There should be an equivalent query_params= method or similar.

我发现了一篇与此相关的好博文,它是 2008 年 10 月的,因此对 Rails 3 不太有用.

There is one good blog post I found related to this and it's from October 2008, so not exactly useful for Rails 3.

更新:我有一个想法.小型 Rack 中间件或 Metal 会解决这个问题吗?它可以直接传递请求,将它的 api_key 附加到.

Update: I had a thought. Would a small Rack middleware or Metal be the answer to this? It could just pass through the request, tacking it's api_key on.

推荐答案

使用 model#prefix_options 它是一个散列,用于将参数传递到查询字符串中(或者甚至作为 Model.prefix 部分的替代,例如 "/myresource/:param/" 将替换为 prefix_options[:param] 的值.前缀中未找到的任何哈希键都将添加到查询字符串中,这正是我们想要的.

Use model#prefix_options which is a hash for passing params into query string (or even as substitions for parts of the Model.prefix, e.g. "/myresource/:param/" will be replaced by the value of prefix_options[:param] . Any hash keys not found in the prefix will be added to the query string, which is what we want in your case).

class Model < ActiveResource::Base
  class << self
    attr_accessor :api_key
  end

  def save
    prefix_options[:api_key] = self.class.api_key
    super
  end
end

Model.site = 'http://yoursite/'
Model.api_key = 'xyz123'
m = Model.new(:field_1 => 'value 1')
# hits http://yoursite:80/models.xml?api_key=xyz123
m.save

这篇关于为 ActiveResource 中的每个请求添加 api 密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆