Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I DRY this code?

This is a Ruby code:

  if (@user.isAdmin?)
    @admin_profile         = AdminProfile.new 
    @user.admin_profile    = @admin_profile 
    @admin_profile.save
    @user.admin_profile_id = @admin_profile.id 
  else        
    @personal_profile = PersonalProfile.new
    @user.personal_profile = @personal_profile
    @personal_profile.save
    @user.personal_profile_id = @personal_profile.id
  end                

Is it possible to DRY this code? Two code is very similar, but as you can see, they have some difference, is it possible to make it simpler?

like image 805
Tattat Avatar asked Dec 05 '25 07:12

Tattat


2 Answers

As a first step you could use the same variable regardless of the profile type i.e.

@profile = @user.isAdmin? ? AdminProfile.new : PersonalProfile.new

This is using Ruby's conditional operator which has the form condition ? value if true : value if false. i.e. if @user.isAdmin? evaluates to true then @profile gets the value after the ?. If @user.isAdmin? is false then @profile gets the value after the :. Notice that because your method name already ends in a ? you get this appearance of a double ?.

and then

if (@user.isAdmin?)
  @user.admin_profile = @profile 
  @user.admin_profile_id = @profile.id 
else        
  @user.personal_profile = @profile
  @user.personal_profile_id = @profile.id
end 

Also, not sure if this is Rails code, but if it is then you don't need to set admin_profile and admin_profile_id, and in fact @profile.id won't be set yet as the profile hasn't saved. So possibly you could reduce the if/else to:

if (@user.isAdmin?)
  @user.admin_profile = @profile 
else        
  @user.personal_profile = @profile
end 

Update

You should also look into the create_association method which you get when you use a belongs_to association. You can have Rails create and save an associated object all in a single step e.g.

@user.create_personal_profile
like image 197
mikej Avatar answered Dec 07 '25 21:12

mikej


what about this to reduce if else

@user.isAdmin? ? @user.admin_profile = @profile : @user.personal_profile = @profile

like image 25
Mayank Jaimini Avatar answered Dec 07 '25 20:12

Mayank Jaimini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!