Add api key to every request in ActiveResource

前端 未结 7 1875
北荒
北荒 2020-12-31 01:20

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 ap

7条回答
  •  情深已故
    2020-12-31 02:18

    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
    

提交回复
热议问题