2014-05-16 1 views
1

senario 내가 App_clients라는 이름의 모델을 가지고 있으며, 트위터와 페이스 북라는 이름의 모델은 모두 그것으로부터 상속 :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]에 따라 app 클라이언트의 인스턴스가 있습니까? 많은 if 또는 elsif를 추가하여 클라이언트를 결정할 필요가 없습니다.

BTW, 전 omniauth를 사용하여 트위터와 페이스 북의 인증을 통합했습니다.

매우 도움을 주셔서 감사합니다.

답변

1

물론 있습니다. 당신이 공급자 요청을받은 경우

당신은 그래서 예를 들어

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

을 사용할 수 있습니다 : "트위터"는 트위터 클래스를 반환합니다.

이 작업을 수행 할 때 약간주의를 기울여야하고 사용자가 잘못 사용하도록 공급자 매개 변수의 유효성을 검사하면됩니다.

또한 read the docs about constantize입니다.

+0

정말 고맙습니다! 잘 작동한다!! – Perpherior

관련 문제