1
Mongoid::Persistable::Creatable::ClassMethods.module_eval do def create(attributes = nil, &block) begin super rescue Mongo::Error::OperationFailure => e Rails.logger.error "failed to create notifications #{e.message}, #{e.backtrace}" raise end end end 

Hello all, I'm trying to override a method from mongoid gem. So I've implemented the above method in config/initializers/mongo.rb, expecting my create method to run as defined in the gem, while leaving error log in case it there is a Mongo::Error::OperationFailure. But instead it gives me this error.

[1] pry(main)> Notification.create(id: 'ididididididid') NoMethodError: super: no superclass method `create' for Notification:Class 

I would like to know why this error occurs and how I can fix it. Thank you.

6
  • Just override it in your notification class. But if you use decent development practices this kind of logging is not needed. Use byebug to step into the controller and write tests that cover the validations. Commented Oct 20, 2017 at 10:34
  • @max Thanks for the advice. The original problem I have is that I have error log Mongo::Error::OperationFailure (can't have multiple _id fields in one document (2)) from the moment I updated my Rails application to 5.1. There was no case of such error while using 5.0. So I need to know where this error log is coming from. Any suggestions? Commented Oct 20, 2017 at 10:36
  • What method are you trying to override? Given your code doesn't work, it would be much easier for you to provide that information than have us dig through the mongoid source code. Commented Oct 20, 2017 at 10:36
  • At a guess though, the easiest way would just be to define your own Notification.create method! Commented Oct 20, 2017 at 10:37
  • You mightg want to create a seperate question about that error - I have not encountered it and it might be bug in mongoid or improper use. Commented Oct 20, 2017 at 10:41

1 Answer 1

7

Monkey patching it directly is hacky and overwrites the method altogether. You expected super to call the original implementation, but it is no longer there. Instead create a new module and include it there:

module CreateWithErrorLogging def create(attributes = nil, &block) begin super rescue Mongo::Error::OperationFailure => e Rails.logger.error "failed to create notifications #{e.message}, #{e.backtrace}" raise end end end Mongoid::Persistable::Creatable::ClassMethods.include CreateWithErrorLogging 
Sign up to request clarification or add additional context in comments.

2 Comments

You can also remove the begin block and rescue the method body.
@Stefan, I wanted to preserve OP's implementation as not to distract him and other readers from the main point.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.