Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ruby - Rails Model name conflict with included gem

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...