Add api key to every request in ActiveResource

前端 未结 7 1824
北荒
北荒 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:09

    I have much nicer solution ! I try with Rack in middleware but i no find any solution in this way....

    I propose you this module for override methods of ActiveReouse::Base

    Add this lib in /lib/active_resource/extend/ directory don't forget uncomment
    "config.autoload_paths += %W(#{config.root}/lib)" in config/application.rb

    module ActiveResource #:nodoc:
      module Extend
        module AuthWithApi
          module ClassMethods
            def element_path_with_auth(*args)
              element_path_without_auth(*args).concat("?auth_token=#{self.api_key}")
            end
            def new_element_path_with_auth(*args)
              new_element_path_without_auth(*args).concat("?auth_token=#{self.api_key}")
            end
            def collection_path_with_auth(*args)
              collection_path_without_auth(*args).concat("?auth_token=#{self.api_key}")
            end
          end
    
          def self.included(base)
            base.class_eval do
              extend ClassMethods
              class << self
                alias_method_chain :element_path, :auth
                alias_method_chain :new_element_path, :auth
                alias_method_chain :collection_path, :auth
                attr_accessor :api_key
              end
            end
          end  
        end
      end  
    end
    

    in model

    class Post < ActiveResource::Base
      include ActiveResource::Extend::AuthWithApi
    
      self.site = "http://application.localhost.com:3000/"
      self.format = :json
    
      self.api_key = 'jCxKPj8wJJdOnQJB8ERy'
    
      schema do
        string  :title
        string  :content
      end
    
    end
    

提交回复
热议问题