Search code examples
ruby-on-railsruby

Override noticed gem delivery method


I'm using noticed Gem version 1.6 with my Rails application. I'm trying to override the delivery method in lib/noticed/delivery_methods/fcm.rb' so when the response returns an error code other than 404, it logs and continues the loop on the devise token. I placed my new version in lib/noticed/delivery_methods/fcm.rb

class Noticed::DeliveryMethods::Fcm < Noticed::DeliveryMethods::Base
  def deliver
    puts"****************************Overrdie is called*****************"
    device_tokens.each do |device_token|
      post("#{BASE_URI}#{project_id}/messages:send", headers: {authorization: "Bearer #{access_token}"}, json: {message: format(device_token)})
    rescue ResponseUnsuccessful => exception
      if exception.response.code == 404
        cleanup_invalid_token(device_token)
      else
        Rails.logger.error("FCM request failed with code #{exception.response.code}: #{exception.message}")
      end
    end
  end
end

yet I'm getting this error NameError (undefined local variable or method `device_tokens' although this method is defined in the original class.


Solution

  • I just realized you made this statement "I placed my new version in lib/noticed/delivery_methods/fcm.rb".

    I believe this is why you are receiving the error because based on your file location it is overriding loading that file from the library itself.

    Instead you want to place this code in the initializers directory. e.g. "config/intializers/noticed_fcm_patch.rb"

    Again I would still recommend appropriate module nesting:

    # config/initializers/noticed_fcm_patch.rb
    
    module Noticed
      module DeliveryMethods
        class Fcm < Base
          def deliver
            puts"****************************Override is called*****************"
            device_tokens.each do |device_token|
              post("#{BASE_URI}#{project_id}/messages:send", headers: {authorization: "Bearer #{access_token}"}, json: {message: format(device_token)})
            rescue ResponseUnsuccessful => exception
              if exception.response.code == 404
                cleanup_invalid_token(device_token)
              else
                Rails.logger.error("FCM request failed with code #{exception.response.code}: #{exception.message}")
              end
            end
          end
        end
      end
    end