简体   繁体   English

我怎么能干这个代码?

[英]How can I DRY this code?

This is a Ruby code: 这是一个Ruby代码:

  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? 两个代码非常相似,但正如您所看到的,它们有一些区别,是否可以使其更简单?

As a first step you could use the same variable regardless of the profile type ie 作为第一步,无论配置文件类型如何,您都可以使用相同的变量

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

This is using Ruby's conditional operator which has the form condition ? 这是使用具有形式条件的 Ruby的条件运算符 value if true : value if false . 值为true如果为false 则为 value ie if @user.isAdmin? 即如果@user.isAdmin? evaluates to true then @profile gets the value after the ? 评估为true然后@profile获取后的值? . If @user.isAdmin? 如果@user.isAdmin? is false then @profile gets the value after the : . 是假的,然后@profile获取@profile的值: 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. 此外,不确定这是否是Rails代码,但如果是,那么您不需要设置admin_profileadmin_profile_id ,实际上@profile.id将不会被设置,因为配置文件尚未保存。 So possibly you could reduce the if/else to: 所以你可以将if/else减少到:

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. 您还应该查看使用belongs_to关联时获得的create_association方法。 You can have Rails create and save an associated object all in a single step eg 您可以让Rails在一个步骤中创建并保存关联的对象,例如

@user.create_personal_profile

what about this to reduce if else 怎么样才能减少if else

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM