2014-05-16 48 views
1

的塞納里奧是我有一個名爲App_clients模型,並命名爲Twitter和Facebook的機型無論是從它繼承:是否有可能在Rails 4中動態創建實例?

Model App 
def initialize(provider,access_token) 
end 

Model Twitter < App 
def initialize(provider, access_token) 
    @client = Twitter::API.new(access_token) 
end 

Model Facebook < App 
def initialize(provider, access_token) 
    @client = Facebook::API.new(access_token) 
end 

我的問題是,是,可能有Apps_controller或模型應用程序的方法來創建應用程序客戶端的實例取決於params [:provider]? 我不想添加到很多if或elsif來決定哪個是客戶端

順便說一句,我使用omniauth集成了Twitter和Facebook的身份驗證。

非常感謝任何幫助

回答

1

當然有。

您可以使用

klass = "#{params[:provider].to_s}".constantize 
instance = klass.new # provide arguments here 

因此,舉例來說,如果你收到提供商的請求:「推特」將返回Twitter的類。

請謹慎操作,並驗證提供者的參數,以免用戶因不良目的而使用它。另外,read the docs about constantize

+0

真的很感謝!它運作良好! – Perpherior

相關問題