简体   繁体   English

从另一个类Ruby调用实例方法

[英]Calling instance method from another class ruby

I am having this runtime error: 我遇到此运行时错误:

11843:E, [2015-05-13T11:00:00.467150 #9464] ERROR -- : 2015-05-13T11:00:00-0400: [Worker(delayed_job host:server pid:9464)] Job CronJob (id=5550d0f84d6f747bcb000000) FAILED with **NoMethodError: undefined method `loadData' for AdminController:Class**

How I can call the method loadData() from the cronJob class? 如何从cronJob类调用方法loadData()? I test the code using the console and it is working fine if I call from console: AdminController.new.loadData() 我使用控制台测试了代码,如果从控制台调用,则可以正常工作: AdminController.new.loadData()

    class AdminController < ApplicationController

    ...

    def setLoadSchedule
        logger.debug "set hour #{params[:admin][:hour]}"
        sethour = params[:admin][:hour]

        Delayed::Job.find(Perseus::Application.config.delayed_job_id).destroy if Perseus::Application.config.delayed_job_id != :nil
    Perseus::Application.config.delayed_job_id = Delayed::Job.enqueue(CronJob.new, cron: '0 ' << sethour << ' * * 1-5')

    hide_action :loadData

    def loadData()
     ...
    end 

    private
    def isAdmin
        if !current_user.admin
        redirect_to root_path
        end
    end

    end

  class CronJob < Struct.new("CronJob")

    def perform
      AdminController.new.loadData()
    end
  end   

Do not create controller by yourself, if you really have to invoke some method of controller in lower part of your application, pass instance of current controller as variable. 不要自己创建控制器,如果确实需要在应用程序的下部调用某些控制器方法,请将当前控制器的实例作为变量传递。

Example: 例:

def index #method of controller AdminController
  CronJob.new(self).perform #so now you are passing controller which inherits from ApplicationController, so loadData method can be invoked on it(if it is public)
end

one more thing, in ruby we write load_data not loadData :) 还有一件事,在ruby中,我们写的是load_data而不是loadData :)

one more thing#2 再一件事#2

if your request is handled by let's say FooController , and you want to invoke method from AdminController it means you should encapsulate load_data method in some third object ( DataLoader ). 如果您的请求由FooController处理,并且您想从AdminController调用方法,则意味着您应该将load_data方法封装在第三个对象( DataLoader )中。 Inheriting in FooController from AdminContorller is not a solution! AdminContorller继承于FooController不是解决方案!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM