2013-04-22 5 views
0

많은 자식 (Tag::Vote, User::Vote, Group::Vote 등)이있는 STI 테이블 (Vote)이 있습니다. 모든 어린이 클래스는 다음과 같습니다 매우 비슷한 방법을 공유레일 : 부모 클래스의 하위 클래스 클래스 이름 가져 오기 방법

def self.cast_vote(params) 
    value = params[:value] 
    vote = Tag::Vote.where(:user_id => User.current.id, 
    :voteable_type => params[:voteable_type], 
    :voteable_id => params[:voteable_id]).first_or_create(:value => value) 
    Vote.create_update_or_destroy_vote(vote, value) 
end 

나는 아이의 클래스 이름을 참조 할 때 다음에 하나 개의 클래스의 유일한 차이는, 두 번째 줄에 있습니다

vote = Tag::Vote.where. . . . 

이 메서드를 부모 클래스로 리팩터링하고 싶습니다.

vote = self.where. . . . 

문제 여기 selfVote보다는 Tag::Vote 또는 User::Vote을 의미한다는 것입니다 : 그것은 거의 내가 함께 두 번째 줄을 교체 할 때 작동합니다. 차례로 type 열 (자식의 클래스 이름이있는 자동 완성)은 자식이 아닌 Vote에서 오는 것이므로 nil로 설정됩니다.

자식 클래스가이 메서드를 상속하고 부모가 아닌 자체를 호출하는 방법이 있습니까?

답변

1

올바르게 유형을 설정하려는 경우 특정 하위 클래스에 대한 지식이 없어도 좋다고 생각하지 않지만 코드를 간소화하여 코드 중복이 훨씬 적습니다. 예 :

class Vote 
    def self.cast_vote_of_type(params, subtype) 
    ....first_or_create(value: value, type: subtype) 
    end 
end 

class Tag::Vote 
    def self.cast_vote(params) 
    cast_vote_of_type(params, self.class.name) 
    end 
end 
+0

이것은 분명히 개선 된 기능입니다. – nullnullnull

관련 문제