Giả sử tôi có một bưu phẩm gửi các email khác nhau, nhưng dự kiến sẽ được gọi với cùng các thông số. Tôi muốn xử lý các thông số đó cho tất cả các hành động gửi thư. Vì vậy, gọi một before_action
mà có thể đọc các thông số gửi đến phương pháp bưu phẩmRails before_action cho ActionMailer có thể sử dụng đối số bưu phẩm
/mailers/my_mailer.rb
class MyMailer < ApplicationMailer
before_filter do |c|
# c.prepare_mail # Will fail, because I need to pass `same_param` arguments
# # I want to send the original arguments
# c.prepare_mail(same_param) # How do I get `same_param` here ?
end
def action1(same_param)
# email view is going to use @to, @from, @context
method_only_specific_to_action1
end
def action2(same_param)
# email view is going to use @to, @from, @context
method_only_specific_to_action2
end
private
def prepare_mail(same_params)
@to = same_params.recipient
@from = same_params.initiator
@context = same_params.context
end
end
Sau đó, trong điều khiển của tôi/dịch vụ tôi làm ở đâu đó
MyMailer.actionx(*mailer_params).deliver_now
Làm thế nào tôi có thể truy cập vào same_param
luận danh sách bên trong khối before_action
?
EDIT:
Tôi muốn cấu trúc lại từ
/mailers/my_mailer.rb
class MyMailer < ApplicationMailer
def action1(same_param)
@to = same_params.recipient
@from = same_params.initiator
@context = same_params.context
method_only_specific_to_action1
end
def action2(same_param)
@to = same_params.recipient
@from = same_params.initiator
@context = same_params.context
method_only_specific_to_action2
end
def actionx
...
end
end
Và đây refactoring
/mailers/my_mailer.rb
class MyMailer < ApplicationMailer
def action1(same_param)
prepare_mail(same_params)
method_only_specific_to_action1
end
def action2(same_param)
prepare_mail(same_params)
method_only_specific_to_action2
end
def actionx
...
end
private
def prepare_mail(same_params)
@to = same_params.recipient
@from = same_params.initiator
@context = same_params.context
end
end
Cảm thấy không tối ưu (prepare_mail(same_params)
nhân đôi trong mọi hành động)
Do đó những gì đã được đề xuất ở trên
chỉ là một suy nghĩ - bạn có nghĩ vì chỉ sử dụng net :: STMP trực tiếp để gửi email http://ruby-doc.org/stdlib-2.0.0 /libdoc/net/smtp/rdoc/Net/SMTP.html.Nó sẽ có thể tùy chỉnh nhiều hơn Action Mailer. – zee
Từ quan điểm kỹ thuật phần mềm, ActionMailer là một bộ điều hợp và bạn có thể cấu hình một số phương thức gửi email (Tôi hiện đang sử dụng 3-4), tôi e rằng SMTP không phải là tất cả trên thế giới, vì vậy tôi muốn sử dụng ActionMailer. –
Tôi nghĩ rằng bạn đang di chuyển một phần logic từ bộ điều khiển vào lớp. Tốt nhất của nó để thêm một lớp dịch vụ/mô hình lớp ở giữa các lớp mailer và bộ điều khiển để đạt được điều này hơn là ghi đè các mailer mặc định để đạt được những gì bạn muốn. – Sairam