Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize this code in Rails?

I have following 4 methods as before filter in my controller, but these have code similarity

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 

How can I optimize this code?

like image 518
Pramod Shinde Avatar asked Nov 26 '25 16:11

Pramod Shinde


1 Answers

You can dynamically create the four validate methods like this:

%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
like image 115
Mischa Avatar answered Nov 28 '25 12:11

Mischa