什么是更像Ruby的方式来执行此命令?

Mat*_*iby 3 ruby ruby-on-rails

我想这样做:

sender_email = @request.user.paypal_email if @request.user.paypal_email == "paypal@anonymous.com"
Run Code Online (Sandbox Code Playgroud)

所以基本上我只想执行命令,如果用户paypal电子邮件是"paypal@anonymous.com".这很好,但似乎有重构的余地.

mon*_*cle 9

@request.user.paypal_email
Run Code Online (Sandbox Code Playgroud)

有些人会主张你只使用一个点'.(参见"Demeter法则".)您可能需要考虑使用Rails'委托'方法

class User < ActiveRecord::Base
  has_many :requests
end

class Request < ActiveRecord::Base
  belongs_to :user

  delegate :paypal_email, :to => :user
end
Run Code Online (Sandbox Code Playgroud)

然后你就可以写了

@request.paypal_email
Run Code Online (Sandbox Code Playgroud)

或者如果你愿意的话

class Request < ActiveRecord::Base
  belongs_to :user

  delegate :paypal_email, :to => :user, :prefix => true
end

@request.user_paypal_email
Run Code Online (Sandbox Code Playgroud)


Pet*_*own 5

由于此代码在您的控制器中,因此它肯定可以重构.您通常希望这样的逻辑在模型中,因为编写单元测试很容易,并且控制器的工作不是很了解用户模型.

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

def User < ActiveRecord::Base
  def sender_email
    paypal_email if paypal_email == "paypal@anonymous.com"
  end
end
Run Code Online (Sandbox Code Playgroud)

然后你的控制器不需要知道太多,可以做:

sender_email = @request.user.sender_email
Run Code Online (Sandbox Code Playgroud)