Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to render a rabl view in a rake task?

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".

like image 333
Marc Avatar asked Apr 03 '12 19:04

Marc


1 Answers

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')
like image 151
mateusmaso Avatar answered Oct 07 '22 16:10

mateusmaso