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
如何優化代碼?
@Mischa ......完美! – LHH
這使代碼幹,但通常「優化」意味着性能。 –
@MarkThomas,以及如何優化這兩行代碼?他在談論代碼相似性,所以我認爲他希望他的代碼更幹。你不這麼認爲嗎? – Mischa