Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Mongoid::Document a GlobalID::Identification for ActiveJobs?

According to the ActiveJobs guide, section 8, it says:

This works with any class that mixes in GlobalID::Identification, which by default has been mixed into Active Model classes.

Mongoid::Document mixes ActiveModel::Model, but I can't find GlobalID::Identification in its included_modules.

  1. Where is GlobalID::Identification defined?

  2. Can I effectively use any Mongoid::Document for my ActiveJobs?

like image 484
Geoffroy Avatar asked Jan 07 '15 13:01

Geoffroy


3 Answers

Put something like this in your initializer:

# config/initalizers/mongoid.rb

if defined?(Mongoid)
  # GlobalID is used by ActiveJob (among other things)
  # https://github.com/rails/globalid

  Mongoid::Document.send(:include, GlobalID::Identification)
  Mongoid::Relations::Proxy.send(:include, GlobalID::Identification)
end
like image 50
sandstrom Avatar answered Nov 14 '22 22:11

sandstrom


There's a mistake in the guides. GlobalID::Identification has been mixed in ActiveRecord. If you mixin GlobalID::Identification into your mongoid documents it will work automatically as GID requires the instance to respond to id (returning the uniq identifier) and the class to respond to find (passing an id will return a record).

like image 16
Cristian Bica Avatar answered Nov 14 '22 22:11

Cristian Bica


To provide more information to anyone having the same problem, you can make it work by simply adding GlobalID::Identification to your models.

class User
  include Mongoid::Document
  include GlobalID::Identification
end

I've actually done that by reopenning Mongoid::Document:

module Mongoid::Document
  include GlobalID::Identification
end

However, I've got some really weird errors sometimes, with ActiveJob which didn't know how to serialize my models. I tried to debug it, but whenever I came into ActiveJob code I had:

pry> User.is_a? GlobalID::Identification
=> true

But ActiveJob::Arguments.serialize_argument didn't work as expected.

The workaround is also to reopen Mongoid::Relations::Proxy:

class Mongoid::Relations::Proxy
  include GlobalID::Identification
end
like image 8
Geoffroy Avatar answered Nov 14 '22 20:11

Geoffroy