在ruby中重构常见的方法参数

时间:2015-02-06 18:19:37

标签: ruby-on-rails ruby refactoring dry

我有一个邮件程序,其方法如下:

def review_comment_notification comment_id, locale = I18n.locale
    comment = Spree::Comment.find(comment_id)
    assign(:review, review_data(comment.commentable))
    assign(:user, user_data(comment.commentable.user))
    assign(:commenter, user_data(comment.user))
    assign(:unsubscribe, unsubscribe_data(self.action))
    assign(:comment, comment_data(comment))
    mail(
      email_id: REVIEW_COMMENT_NOTIFICATION_TEMPLATE,
      recipient_address: comment.commentable.user.email,
      version_name: localized_version(locale)
    )
  end

  def store_credit_receipt(user_id, store_credit_id, locale = I18n.locale)
    store_credit = Spree::StoreCredit.find(store_credit_id)
    user = Spree::User.find(user_id)
    assign(:user, user_data(user))
    assign(:store_credit, store_credit_data(store_credit))
    assign(:unsubscribe, unsubscribe_data(self.action))
    mail(
      email_id: STORE_CREDIT_RECEIPT_TEMPLATE,
      recipient_address: user.email,
      version_name: localized_version(locale)
    )
  end

  def reset_password_instructions user, store_id, locale = I18n.locale
    # Dual handling here kept due to external libraries.
    user = user.respond_to?(:id) ? user : Spree::User.find(user)
    set_store(Spree::Store.find(store_id)) if store_id
    password_reset_url = spree.edit_password_url(
      reset_password_token: user.reset_password_token
    )
    assign(:password_reset_url, password_reset_url)
    mail(
      email_id: RESET_PASSWORD_INSTRUCTIONS_TEMPLATE,
      recipient_address: user.email,
      version_name: localized_version(locale)
    )
  end

  def welcome user_id, store_id, locale = I18n.locale
    user = Spree::User.find(user_id)
    set_store(Spree::Store.find(store_id)) if store_id
    assign(:user, user_data(user))
    mail(
      email_id: WELCOME_TEMPLATE,
      recipient_address: user.email,
      version_name: localized_version(locale)
    )
  end

现在我们需要在运行时使用当前的语言环境来决定要发送的电子邮件的版本。另请注意,这不是标准的ActionMailer邮件程序。

问题是,要实现这一点,我必须将locale = I18n.locale添加到所有邮件中的EVERY方法。

这对我来说是个主要气味。但是因为我在方法调用时需要语言环境,所以我不能将它作为类默认值(除非我遗漏了一些东西)

有没有办法重构这个添加的逻辑呢?

1 个答案:

答案 0 :(得分:2)

这些是实例方法,对吧?当一个对象需要数据时到处做什么,在构造期间传递它:

mailer = WhateverMailer.new(locale: I18n.locale)
mailer.welcome(user_id, store_id)

因此,您只需将语言环境存储为邮件程序中的实例变量即可。看看其他方法,似乎该模式可以帮助清理其他内容,例如user_id