2014-09-25 81 views
1

我有一個從類(Popsicles)生成的對象,它正在傳遞給另一個類(PopsicleProcessor),只有Popsicle對象的ID,這是'保證'(UUID)是獨特。如何從PopsicleProcessor類訪問Popsicle對象,而不必像傳遞整個Popsicle對象那樣做一些不好的事情?Ruby/Rails通過ID查找對象

我的應用程序沒有數據庫來查找這些對象,它們純粹存在於應用程序的內存中,直到處理完成。

我真的不知道如何實現這一點,特別是因爲它被卸載到Resqueue隊列上,它將再次啓動應用程序的整個實例 - 因此傳遞對象本身會導致巨大的性能損失(縮放) ,從我所知道的。

一般來說,這是怎麼做的(因爲Resqueue根本不應該有所作爲)。

我想能夠從另一個類訪問對象實例變量和方法。

下面是我現在正在做的事情,這是行不通的。

popsicles.rb

class Popsicles 

    require "securerandom" 

    @someID 


    def initialize params 

     @someID = SecureRandom.uuid 

    end 

    def doSomething 

     Resque.enqueue(popsicleProcessor, @someID) 

    end 

end 

popsicles_processor.rb

# Worker class 
class PopsiclesProcessor 

    # Requires a @queue instance variable 
    @queue = :popsicle_queue 

    # Needs to take same argument we passed to enqueue method 
    def self.perform(popsicle_id) 

    # Get the object somehow 

    # Now we can call other methods like changeFlavour, or whatever 

    end 

end 

回答

2

,你的工人在不同的進程中運行的事實,實際上是相關的,因爲這將有自己的記憶沒有訪問主應用程序進程中創建的Popsicle對象的空間。如果您只想通過另一個進程中的ID加載它們,您需要有一些方法來保存Popsicle對象。如果不能使用數據庫,則必須序列化對象或將其數據的各個組件傳遞給工作者,以便可以在工作進程中重新構建它。