Viet
Viet

Reputation: 583

Can not call method of other class from static method

At first, i have a class which in app/workes/ like this:

class SendMailTask
  include Resque::Plugins::Status
  require 'mail'
  def perform
    ...
  end

And as a controller, i have class UsersController and a static method like bellow:

class UsersController < ApplicationController
  def self.check
    ...
    ::SendMailTask.create(to: [] << @to_addresses,  subject: @subject, body: @body)
  end

When i call method UsersController.check() from other file, i received the error: "in `block in check': uninitialized constant SendMailTask (NameError)"

But from other controller, i can call SendMailTask normally:

class ErrorController < ApplicationController
  def index
    ...
    ::SendMailTask.create(to: [] << @to_addresses,  subject: @subject, body: @body)
  end

I try to add this line:

config.autoload_paths += %W(#{config.root}/app/workers)

to application.rb and try to add

require './SendMailTask'

at the begin of file users_controller.rb but it does not work.

Please help me resolve this error. Thanks you

Upvotes: 0

Views: 136

Answers (1)

CuriousMind
CuriousMind

Reputation: 34145

NameError means the your SendMailTask isn't loaded. so you will have to load that. so couple of things.

  1. I noticed a typo workes, so please verify the file name is correct. By Convention, it should be located at app/workers/send_mail_task.rb. so kindly double-triple check the same.

  2. About require './SendMailTask', this is wrong. Instead it would be send_mail_task as requires works on filenames & not class names.

  3. if still get an error, then please post your $LOAD_PATH to see you are requiring the file relative to the defined $LOAD_PATH

  4. Instead of require, I prefer to use require_dependency as it works with code-reloading etc. so if you have trouble with auto-loading, just stick that require_dependency on top of the file, this will hint rails to load the file BEFORE running the controller.

Upvotes: 1

Related Questions