ruby on rails - How does format.html know what to render? -
i have following piece of code in file app/mailers/user_mailer.rb . how format.html know render . not in action of controller. understand basic fact renders show view default here no controller no action. how still work ?
class usermailer < actionmailer::base def signup_notification(user) @recipients = "#{user.email}" @from = "#{sender.email}" mailer_name = "signup_notification" mail(:to => @recipients, :from => @from) |format| format.html end end
you're right actionmailer not controller (that's actioncontroller). respond_to
method of actioncontroller , mail
method of actionmailer entirely different things, both have concept of "what kind of response should sending" , rails devs chose offer similar interface format picking in both.
in actioncontroller respond_to
method takes block , uses http request environment pick format render.
in actionmailer, mail
takes block , uses different logic decide format render. when give format.html
looks in views folder templates <method_name>.<format>.<acceptable_template_type>
, e.g., signup_notification.html.erb. aside, should name methods in snake_case (signup_notification). uppercase method names non-idiomatic , might cause problems.
technical explanation
while don't need know use actionmailer, think it's interesting walk through flow of how template generation works here. includes interesting meta-programming logic simpler in regular controllers (no http environment).
you can see in source mail calls a function render messages. if gave mail
block, mail creates instance of actionmailer::collector (which includes abstractcontroller::collector) , yields collector. so, in example collector gets function html
called on (since do |format| ... end
has argument, format
collector instance when yield(collector)
called here.
so instance of actionmailer::collector passed do |format| ...
block, has function html
called on it, collector uses method missing tricks abstractcontroller::collector can respond mime type, passing requested type on actionmailler::collector#custom
builds email looking in views folder templates matching type.
Comments
Post a Comment