ruby-on-rails – 将选项哈希传递给sidekiq worker

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 将选项哈希传递给sidekiq worker前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我记得当我尝试将params( JSON)选项传递给sidekiq工作方法时它并没有很好用,因为我引用了以下选项:
options[:email_address]

但我认为如果我这样做会有效:

options["email_address"]

因此,出于某种原因,当它被序列化和反序列化时,哈希只能用字符串而不是符号来引用.

这是安全的做法吗?

我有一个交易电子邮件工作者,看起来像:

class TransactionEmailWorker
    include Sidekiq::Worker

  def perform(action,options)
    case action
    when 'welcome'
      welcome(options["email_address"],options["something_else"])
    when 'reset_password'
      reset_password(options["email_address"])
    end
  end

  def welcome(email,title)
    # ...
  end

  def reset_password(email)
   # ..
  end

解决方法

这就是Sidekiq wiki page所说的:

The arguments you pass to perform_async must be composed of simple JSON datatypes: string,integer,float,boolean,null,array and hash. The Sidekiq client API uses JSON.dump to send the data to Redis. The Sidekiq server pulls that JSON data from Redis and uses JSON.load to convert the data back into Ruby types to pass to your perform method. Don’t pass symbols,named parameters or complex Ruby objects (like Date or Time!) as those will not survive the dump/load round trip correctly.

传递Ruby哈希是有效的,因为它能够序列化为有效的JSON.所以回答你的问题,这是安全的做法.

serialized_args = JSON.dump({email_address: "someemailaddress@gmail.com",something_else: "thing"})
=> "{\"email_address\":\"someemailaddress@gmail.com\",\"something_else\":\"thing\"}"

JSON.load(serialized_args)
=> {"email_address"=>"someemailaddress@gmail.com","something_else"=>"thing"}

猜你在找的Ruby相关文章