how to render a rabl view in a rake task?

喜你入骨 提交于 2019-12-10 13:08:49

问题


I'm trying to render a rabl view to string in a rails 3.2 rake task. I'm rendering it to string in order to send some JSON through Pusher from a background task. I've looked at various render_to_string from rake task answers but none of them seem to work. Here is what I have thus far:

controller = PostsController.new
av = ActionView::Base.new(MyApp::Application.config.paths['app/views'].first,{},controller)
@post = post
Pusher["some channel"].trigger('new_post', av.render(:template => 'posts/show.json.rabl'))

With this attempt I get a ActionView::Template::Error exception and the error "undefined method `parameters' for nil:NilClass".


回答1:


There is an easier way to do that which is by calling Rabl::Renderer methods. However your context will matter when you try to render something. Therefore, be careful if there is any controller/helper methods inside your rabl files because they will not be available when calling it outside. Here is a sample code that you can use, tested with Rabl 0.6.13.

Rabl::Renderer.json(@post, 'posts/show', :view_path => 'app/views')


来源:https://stackoverflow.com/questions/9999789/how-to-render-a-rabl-view-in-a-rake-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!