如何在rake任务中渲染rabl视图? [英] how to render a rabl view in a rake task?

查看:72
本文介绍了如何在rake任务中渲染rabl视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试渲染rabl视图以在rails 3.2 rake任务中进行字符串化.我将其呈现为字符串,以便从后台任务通过Pusher发送一些JSON.我已经从rake任务答案中查看了各种render_to_string,但是它们似乎都不起作用.到目前为止,这是我所拥有的:

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'))

通过这种尝试,我得到一个ActionView :: Template :: Error异常和错误"nil:NilClass的未定义方法'parameters'".

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

推荐答案

还有一种更简单的方法,那就是调用 Rabl :: Renderer方法.但是,当您尝试渲染某些内容时,上下文会很重要.因此,请注意您的rabl文件中是否包含任何控制器/帮助程序方法,因为在外部调用它们时将无法使用它们.这是您可以使用的示例代码,并经过Rabl 0.6.13的测试.

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')

这篇关于如何在rake任务中渲染rabl视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆