module Postjob::Queue::Encoder

The Postjob::Queue::Encoder module wraps the JSON encoder, to ensure that only our data is encoded.

Workflows should exclusively use Numbers, true, false, nil, Strings, Times and Dates, and Arrays and Hashes built of those.

postjob does not support all data types supported by Ruby's “json” library. We do not support Symbols, but might also not support things like ActiveRecord objects etc.

Public Instance Methods

check_encodable!(data) click to toggle source
# File lib/postjob/queue/encoder.rb, line 19
def check_encodable!(data)
  encode(data)
end
encode(data) click to toggle source
# File lib/postjob/queue/encoder.rb, line 23
def encode(data)
  return nil if data.nil?

  verify_encodable!(data)
  ::JSON.generate(data)
rescue ::JSON::JSONError, ::EncodingError
  raise ::Postjob::Error::Encoding, $!.to_s
end

Private Instance Methods

verify_encodable!(obj) click to toggle source
# File lib/postjob/queue/encoder.rb, line 34
def verify_encodable!(obj)
  case obj
  when nil, true, false then :ok
  when String then :ok
  when Numeric then :ok
  when Time, Date, DateTime then :ok
  when Hash  then verify_encodable!(obj.keys) && verify_encodable!(obj.values)
  when Array then obj.each { |entry| verify_encodable!(entry) }
  else
    msg = "Unencodable #{obj.class.name} object: #{obj.inspect}"
    raise ::Postjob::Error::Encoding, msg
  end
end