Tattat
Tattat

Reputation: 15778

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?

Upvotes: 3

Views: 162

Answers (2)

Mayank Jaimini
Mayank Jaimini

Reputation: 61

what about this to reduce if else

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

Upvotes: 1

mikej
mikej

Reputation: 66263

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

Upvotes: 5

Related Questions