将HTTParty与delayed_job一起使用

时间:2011-12-12 20:57:47

标签: ruby-on-rails delayed-job httparty

我正在尝试使用delayed_jobHTTParty

执行此操作
HTTParty.delay.get('http://example.com')

它成功保存到DJ表中:

--- !ruby/object:Delayed::PerformableMethod
object: !ruby/object:Module {}
method_name: :get
args:
- http://example.com

问题是它在该处理程序中没有提及HTTParty,因此当我尝试运行作业时,我收到此错误:

undefined method `get' for #<Module:0x007fff1095b9a8>

我在delayed_job (3.0.0.pre)应用中使用delayed_job_active_record (0.2.1)httparty (0.7.7)rails 3.0.6

那么我怎么能让delayed_job和HTTParty一起玩得很好呢?

1 个答案:

答案 0 :(得分:1)

将代码包装在实例方法中。

示例:

# User.rb model
include HTTParty

# Get a URL
def start_the_party(url)
  HTTParty.get(url)
end
handle_asynchronously :start_the_party

然后你只需将它称为其他地方:

some_user.start_the_party

或者如果您需要访问成功的获取请求内容

some_results = some_user.start_the_party

修改

如果你打算把它变成一个类方法,那么代码将是这样的:

示例:

# User.rb model
include HTTParty

# Get a URL
class << self
  def start_the_party(url)
    HTTParty.get(url)
  end
  handle_asynchronously :start_the_party
end

然后你只需将它称为其他地方:

User.start_the_party

或者如果您需要访问成功的获取请求内容

some_results = User.start_the_party

区别在于User.some_method_name模型上调用User,而some_user.some_method_name模型的实例(即当前用户对象)调用User。 / p>