2017-04-16 81 views
0

我有兩個「引擎」處理特定的工作,他們每個人都使用不同的工具/ apis。我有一個Engine模型,它保存它們之間的通用數據/行爲,但每個Engine都有其他特定的字段/方法。如何動態選擇一個Rails模型來實例化?

class Engine 
    field :name 
    field :status 
end 

class DefaultEngine 
    field :job_id 

    def process 
    # default engine process 
    # ... 
    end 
end 

class SpecialEngine 

    def process 
    # special engine process 
    # ... 
    end 
end 

class Site 
    field :engine, type: String, default: '::DefaultEngine' 
end 

我想要做的就是讓Engine負責繼承正確的引擎,這取決於site.engine值。例如,在控制器中,我想要執行以下操作:

def start 
    job = Engine.create() 
    job.process 
end 

我不想直接引用任何引擎。相反,我想Engine負責找出哪個是正確的引擎使用。什麼是處理這種情況的方法,以便Engine.create可以返回SpecialEngineDefaultEngine的實例。

回答

1
class Site 
    field :engine, type: String, default: '::DefaultEngine' 

    def engine_class 
    @engine_class ||= engine.constantize 
    end 
end 

def start 
    job = site.engine_class.create 
    job.process 
end 
3

由於這標誌着ruby-on-rails,您可以使用constantize

site.engine # => 'SpecialEngine', your string field 
site.engine.constantize # => SpecialEngine, class 
site.engine.constantize.new # => #<SpecialEngine:0x007fc52c9893a8>, engine instance 
相關問題