2014-05-01 78 views
2

我有以下4種方法在我的控制器過濾器之前,但是這些代碼相似度如何在Rails中優化這段代碼?

before_filter :load_person, except: [:autocomplete] 
before_filter :validate_twitter, only: [:recent_tweets, :commonly_following] 
before_filter :validate_linkedin, only: [:common_connections] 
before_filter :validate_facebook, only: [:mutual_friends] 
before_filter :validate_google, only: [:meetings] 

def validate_linkedin 
    @linkedin_account = current_user.social_account("LinkedIn") 
    return render json: { message: "You are not connected to your LinkedIn account" } if @linkedin_account.blank? 
    return render json: { message: "No Linkedin url for #{@person.name}" } if @person.linkedin_url.blank? 
end 

def validate_twitter 
    @twitter_account = current_user.social_account("Twitter") 
    return render json: { message: "You are not connected to your Twitter account" } if @twitter_account.blank? 
    return render json: { message: "No Twitter username for #{@person.name}" } if @person.twitter_username.blank? 
end 

def validate_facebook 
    @facebook_account = current_user.social_account("Facebook") 
    return render json: { message: "You are not connected to your Facebook account" } if @facebook_account.blank? 
end 

def validate_google 
    @google_account = current_user.social_account("Google") 
    return render json: { message: "You are not connected to your Google account" } if @google_account.blank? 
end 

def load_person 
    @person = Person.where(id: params[:id]).first 
    return render json: { message: "Cannot find the person with id: #{params[:id]}"} if @person.blank? 
end 

如何優化代碼?

回答

9

您可以動態創建四個驗證方法是這樣的:

%w{LinkedIn Twitter Facebook Google}.each do |social_media| 
    define_method "validate_#{social_media.downcase}" do 
    instance_variable_set("@#{social_media.downcase}_account", current_user.social_account(social_media)) 
    return render json: { message: "You are not connected to your #{social_media} account" } if instance_variable_get("@#{social_media.downcase}_account").blank? 
    end 
end 
+0

@Mischa ......完美! – LHH

+0

這使代碼幹,但通常「優化」意味着性能。 –

+0

@MarkThomas,以及如何優化這兩行代碼?他在談論代碼相似性,所以我認爲他希望他的代碼更幹。你不這麼認爲嗎? – Mischa