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

时间:2015-02-24 15:55:45

标签: ruby-on-rails

我有两个班级:

1)负责发出HTTP请求的API(ApiClient)(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 :: Callbacks设置了它。

我很好奇如何在AuditTrail函数中访问我的函数参数?例如,当我输入AuditTrail.after_post函数时,有没有办法从post函数访问路径,数据,标题和响应?

1 个答案:

答案 0 :(得分:0)

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