Rails 3: How to render ERb template in rake task?

前端 未结 4 1564
无人及你
无人及你 2020-12-25 15:17

I am rendering a pretty huge sitemap HTML file with rake. Unfortunately, the code breaks when I migrate to rails 3. My current code looks like this:

@control         


        
相关标签:
4条回答
  • 2020-12-25 15:24

    This is what worked for me:

    html = render_to_string(:index, layout: nil)
    
    0 讨论(0)
  • 2020-12-25 15:28

    One of the approaches works when I include Rails.application.routes.url_helpers instead of ActionView::Helpers::UrlHelper. This works for now:

    include Rails.application.routes.url_helpers # brings ActionDispatch::Routing::UrlFor
    include ActionView::Helpers::TagHelper
    
    av = ActionView::Base.new(Rails.root.join('app', 'views'))
    av.assign({
      :regions => @regions,
      :courts_by_region => @courts_by_region,
      :cities_by_region => @cities_by_region,
      :districts_by_region => @districts_by_region
    })
    f = File.new(file_name, 'w')
    f.puts(av.render(:template => "sitemap/index.html"))
    f.close
    

    Hope this helps others. If there is a better solution, I'd be interested.

    Also, how do I automatically get a hash of assigns from binding?

    0 讨论(0)
  • 2020-12-25 15:34

    This is what worked for me (Rails 3):

    class TaskActionView < ActionView::Base
      include Rails.application.routes.url_helpers
      include ApplicationHelper
    
      def default_url_options
         {host: 'example.com'}
      end
    end
    
    def action_view
      controller = ActionController::Base.new
      controller.request = ActionDispatch::TestRequest.new
      TaskActionView.new(Rails.root.join('app', 'views'), {}, controller)
    end
    
    action_view.render(:template =>"path/to/template")
    

    This successfully included my application helper, tag helpers, and url helpers. You'll want to put your application/environments host properly into the default_url_options hash.

    0 讨论(0)
  • 2020-12-25 15:40

    I was successfull by doing something like this:

    class Template < ActionView::Base
      include Rails.application.routes.url_helpers
      include ActionView::Helpers::TagHelper
    
      def default_url_options
        {host: 'yourhost.org'}
      end
    end  
    
    template = Template.new(Rails.root.join('app', 'views'))
    template.assign(attendee: @attendee)
    template.render(template: 'sitemap/index.html.erb')
    
    0 讨论(0)
提交回复
热议问题