Rails Model name conflict with included gem

2020-04-15 01:49发布

We've been mocking up our email jobs with success until we actually included our SendGrid Gem at the top of our worker

require 'sendgrid-ruby'
include SendGrid

class Notifications::WelcomeWorker
  include Sidekiq::Worker

  def perform(email_id)

    emailAddr = Email.find(email_id)
    ...
  end
end

The problem seems to arise because SendGrid has the same model within (Email)

thus generating the message

undefined method `find' for SendGrid::Email:Class

I've tried calling Email via ApplicationRecord::Email to be more context specific but to no avail.

All the SO and other guides generally go with change our model name, but I feel like there must be a better way. To be clear we are running Rails 5 so I'm wondering if theres been an update in it to address this issue which I simply haven't found.

1条回答
Emotional °昔
2楼-- · 2020-04-15 02:31

include SendGrid it the culprit.

It adds all constants from the SendGrid module to the current module (which is probably the top level), so you can use SendGrid's classes without prefix, e.g. just Email.new instead of SendGrid::Email.new.

The downside is that it also messes with your existing constants.

You can either include it under a specific module:

class Notifications::WelcomeWorker
  include Sidekiq::Worker
  include SendGrid

  # ...
end

Then, Email resolves to Sendgrid::Email and ::Email resolves to your top-level Email class.

Or you could simply remove the include SendGrid line and use the SendGrid:: prefix.

查看更多
登录 后发表回答