ActiveModel::回调访问回调函数中的属性



我有两个类:

1) API(ApiClient),负责发出HTTP请求(GET、PUT、POST、DELETE)。

require 'faraday'
module Assets
  class ApiClient
    extend ActiveModel::Callbacks
    define_model_callbacks :post, :put, :delete
    after_post Assets::AuditTrail
    after_put Assets::AuditTrail
    after_delete Assets::AuditTrail
    def initialize(url, username = nil, password = nil)
      @connection = Faraday.new(url) do |faraday|
        faraday.basic_auth(username, password)
        faraday.request :url_encoded # form-encode POST params
        faraday.response :logger # log requests to STDOUT
        faraday.adapter :net_http # make resusts with Net::HTTP
        faraday.use Errors::RaiseError # include custom middleware
      end
    end
    def get(path, parameter = nil)
      @connection.get path, parameter
    end
    def post(path, data, headers = {})
      response = @connection.post path, data, headers
      run_callbacks :post
      return response
    end
    def put(path, data, headers = {})
      response = @connection.put path, data, headers
      run_callbacks :put
      return response
    end
    def delete(path)
      response = @connection.delete path
      run_callbacks :delete
      return response
    end
  end
end

2) 负责记录到数据库的审计跟踪(AuditTrail)。

module Assets
  class AuditTrail
    def self.after_post(obj)
      puts 'IN THE AFTER POST!!!'
    end
    def self.after_put(obj)
      puts 'IN THE AFTER PUT!!!!'
    end
    def self.after_delete(obj)
      puts 'IN THE AFTER DELETE!!!!'
    end
  end
end

每次发出PUT、POST或DELETE请求时,我都希望通过AuditTrail类将事务记录在数据库中。我使用ActiveModel::回调进行设置。

我很好奇如何访问AuditTrail功能中的功能参数?例如,当我输入AuditTrail.after_post函数时,是否有方法访问post函数的路径、数据、标头和响应?

回调方法中的obj参数是对调用回调的ApiClient实例的引用。我认为,如果将调用响应存储到实例变量中,那么应该能够在回调方法中解析所需的数据。

最新更新