如何在Rails中优化此代码?

时间:2014-05-01 14:41:44

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我在控制器中有以下4种方法,但这些方法具有代码相似性

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 

如何优化此代码?

1 个答案:

答案 0 :(得分: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