【问题标题】:How to optimize this code in Rails?如何在 Rails 中优化这段代码?
【发布时间】:2014-05-01 14:41:44
【问题描述】:

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

如何优化这段代码?

【问题讨论】:

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


    【解决方案1】:

    您可以像这样动态创建四个验证方法:

    %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 进行优化,Mischa 的代码很棒(我赞成)。如果优化可读性,我认为原始代码更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多