执行此命令的更像 Ruby 的方式是什么? [英] What is a more Ruby-like way of doing this command?

查看:46
本文介绍了执行此命令的更像 Ruby 的方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

sender_email = @request.user.paypal_email if @request.user.paypal_email == "paypal@anonymous.com"

所以基本上我只想在用户的 paypal 电子邮件是 "paypal@anonymous.com" 时才执行命令.这工作正常,但似乎有重构的空间.

So basically I want to only execute the command if the users paypal email is "paypal@anonymous.com". This works fine but it seems like there is room for refactoring.

推荐答案

既然这段代码在你的控制器中,那么它肯定是可以重构的.您通常希望在模型中包含这样的逻辑,因为编写单元测试很容易,而且了解用户模型的信息不是控制器的工作.

Since this code is in your controller, then it can definitely be refactored. You typically want logic like this to be in the models since it's easy to write unit tests and it's not the job of the controller to know so much about the user model.

有几种方法可以重构它,但我建议将逻辑移至用户模型,如下所示:

There's a few ways you could refactor this, but I would recommend moving the logic to the user model like so:

def User < ActiveRecord::Base
  def sender_email
    paypal_email if paypal_email == "paypal@anonymous.com"
  end
end

那么你的控制器就不需要知道那么多,就可以做:

Then your controller wouldn't need to know as much and could just do:

sender_email = @request.user.sender_email

这篇关于执行此命令的更像 Ruby 的方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆