问题
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