k0kubun / hamlit

High Performance Haml Implementation
https://rubygems.org/gems/hamlit
Other
981 stars 59 forks source link

Rendering in ActionMailer doesn't work #119

Closed ghost closed 6 years ago

ghost commented 6 years ago

I'm doing something like this

class ApplicationMailer < ActionMailer::Base
end

class NotificationMailer < ApplicationMailer
  def notify
    @message = 'email notification'

    mail to: 'dummy@example.com'
  end

  def mail(headers = {}, &block)
    template = MailTemplate.find_by(key: "#{mailer_name}/#{action_name}")
    super(headers, &override_block(template))
  end

  private

  def override_block(template)
    binding_obj = view_context.instance_eval { binding }

    Proc.new do |format|
      format.html { render html: template.render(binding_obj) }
    end
  end
end

class MailTemplate < ActiveRecord::Base
  def render(binding_obj)
    case filetype
    when 'erb' then ERB.new(body).result(binding_obj)    
    when 'haml' then Hamlit::Template.new { body }.render(binding_obj).html_safe
    # when 'haml' then Haml::Engine.new(body).render(binding_obj)
    end
  end
end

It works fine in haml (where commented out)

MailTemplate.create(filetype: :haml, body: '%p=@message', key: 'notification_mailer/notify')

NotificationMailer.notify.deliver_now
=> <p>email notification</p>

But in hamlit (2.8.7) it instead returns like this

NotificationMailer.notify.deliver_now
=> <p></p>
ghost commented 6 years ago

I solved it by the following.

Hamlit::Template.new { body }.render(view_context)