2014-12-07 36 views
0

方法内可以达到方法吗?例如:可以在方法内调用方法吗?

class HardWorker < WebsocketRails::BaseController 
    def perform 
    self.main_method 
    end 

    def main_method 
    puts "main method" 

    def simple_method # how to call this from outisde? 
     puts "simple method" 
    end 

    def another_method 
     puts "another_method" 
     # do stuff 
    end 
    another_method  #start running "another method in background" 
    end 
end 

而且我需要达到“主要方法”内的“simple_method”。

WebsocketRails::EventMap.describe do # now it works like that: 
    subscribe :event_name, :to => HardWorker, :with_method => :main_method 
end 

触发:event_name,我的控制台上后说:"main method"。但我需要在那里写"simple method",而无需重新启动main_method。我需要在main_method以内达到simple_method。 Becouse main_method已经在后台运行,我需要在其内部实现一种方法并进行许多计算。我使用sidekiq,所以我不能使用main_method范围以外的全局变量。我想我需要它的工作,如:

WebsocketRails::EventMap.describe do # i wish it works, but it doesn't 
    subscribe :event_name, :to => HardWorker, :with_method => :main_method[:simple_method] 
end 

更新:我需要更新此@global_object。如果我记得“main_method”,我会放弃本地递增的@global_object。我需要它在本地增加,但我不记得main_method。

def main_method 

    @global_object = 0 

    def simple_method 
     @global_object += 100 
    end 

    def another_method 
     (1..(2**(0.size * 8 -2) -1)).each do |number| 
     # every second updating my data and sending to Redis DB 
     @global_object++ 
     sleep 1 
     end 
    end 
    another_method 
    end 

回答

1

你不清楚你在问什么,但是如果你想定义类方法,为什么不定义类方法呢?

class HardWorker < WebsocketRails::BaseController 
    def perform 
    self.main_method 
    end 

    def self.main_method 
    puts "main method" 
    self.simple_method 
    self.another_method  #start running "another method in background" 
    end 

    def self.simple_method # how to call this from outisde? 
    puts "simple method" 
    end 

    def self.another_method 
    puts "another_method" 
    # do stuff 
    end 
end 
+0

Thx for answer。我更新了我的问题。 – mansim 2014-12-07 15:37:06

相关问题