Cannon Moyer
Cannon Moyer

Reputation: 3174

Conflicting Class Name in Rails

I'm trying to use the sendgrid-ruby API to send emails. I have a Attachment model that I use to keep track of uploaded files in an AWS bucket.

I just tried running bundle install after setting

gem 'sendgrid-ruby' 

in my Gemfile, but upon loading the app after installing the gem, I get the following error:

TypeError (superclass mismatch for class Attachment):

app/models/attachment.rb:1:in `<top (required)>'
app/controllers/jobs_controller.rb:182:in `edit'

Is there anyway to fix this without changing the name of my model?

UPDATE:

My SendGridEmail class:

require 'sendgrid-ruby'
include SendGrid

class SendGridEmail

  def initialize 
  end

  def send_message
    mail = Mail.new
    mail.from = Email.new(email: '[email protected]')
    mail.subject = 'I\'m replacing the subject tag'
    personalization = Personalization.new
    personalization.add_to(Email.new(email: '[email protected]'))
    personalization.add_substitution(Substitution.new(key: '-name-', value: 'Example User'))
    personalization.add_substitution(Substitution.new(key: '-city-', value: 'Denver'))
    mail.add_personalization(personalization)
    mail.add_content(Content.new(type: 'text/html', value: 'I\'m replacing the <strong>body tag</strong>'))
    mail.template_id = '7fd8c267-9a3c-4093-8989-3df163e87c47'

    sg = SendGrid::API.new(api_key: "xxxxxxxxxxxxxxxxxxxxxx")
    begin
        response = sg.client.mail._("send").post(request_body: mail.to_json)
    rescue Exception => e
        puts e.message
    end
    puts response.status_code
    puts response.body

    puts response.headers
  end

  def create_notification
    @customer.notifications.create(name: "Manually Text Job to Customer", to: "+1", notification_type: "Manual Job Notification")
  end
end

Upvotes: 1

Views: 187

Answers (1)

tadman
tadman

Reputation: 211740

Using include messes up namespaces, so it's best to just not do that. Ruby has a singular global namespace unlike things like Python and Node, so you need to be very careful when importing.

If you include SendGrid and that has a SendGrid::Attachment class then Ruby will try and reconcile that with your Attachment class later, which will fail.

The best plan is to update your code to include the SendGrid:: prefix on everything. A well-designed library will be cleanly namespaced to avoid this problem.

Upvotes: 3

Related Questions