Ruby on rails 如何在Rails中优化此代码?

Ruby on rails 如何在Rails中优化此代码?,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,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_fa

在我的控制器中,我有以下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 

如何优化此代码?

您可以动态创建以下四种验证方法:

%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

这会使代码变得枯燥,但通常“优化”意味着性能。@MarkThomas,那么如何优化这两行代码呢?他说的是代码相似性,所以我认为他希望他的代码更加枯燥。你不这样认为吗?是的,我这样认为。我想我的评论更多的是针对OP。为了解决linkedin的大写问题,你可以首先传递正确大写的版本,然后在方法/变量名中使用它们(保留它们在消息中的原样)。这取决于你优化的目的。如果针对DRY进行优化,Misha的代码很棒(我投了更高的票)。如果优化可读性,我认为原始代码更好。