我如何通过rake任务将对象传递给rabl视图 [英] How can I pass an object to rabl views from rake task

查看:114
本文介绍了我如何通过rake任务将对象传递给rabl视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用rabl从rake任务创建一个json文件.下面是我要测试的简化版本.

I am trying to create a json file from a rake task using rabl. Below I have the simplified version to test with.

当我通过网址查看"articles.json"或"articles/2.json"时,我得到了预期的json响应.

When I view 'articles.json' or 'articles/2.json' via the url, I get the expected json response.

但是,当我尝试通过rake任务运行它时,在创建的jsonFile中,@ articles的值始终为空.它将使index.json.rabl视图的显示次数与@ articles.count相同,但是该值始终为null.

But when I try to run it via the rake task, it always has a null value for @articles in the jsonFile created. It will render the index.json.rabl view the same number of times as @articles.count, but the values are always null.

那么如何将我在rake任务中创建的@articles对象传递给Rabl.render?

So how do I pass in the @articles object created in my rake task to Rabl.render?

@feedName ||= 'default'
node(:rss) { partial('articles/rss), :object => @feedName }
node(:headlines) { partial('articles/show'), :object => @articles }

show.json.rabl

object @article
attributes :id,:body
....

exports.rake

task :breakingnews => :config do
  filename = 'breakingnews.json'
  jsonFile = File.new(filename)
  @articles = Article.limit(10)
  n = Rabl::renderer.json(@articles,'articles/index',view_paths => 'app/views')
  jsonFile.puts b
  jsonFile.close

推荐答案

我遇到了类似的问题.您基本上有2个选择:

I ran into a similar problem. You basically have 2 options:

  1. 明确地将单个对象作为参数传递
  2. 根据范围隐式传递多个对象
  1. Pass a single object explicitly as a parameter
  2. Pass multiple objects implicitly by scope

按参数

在您的任务中

@your_object = ...
Rabl.render(@your_object, 'your_template', view_paths => 'relative/path/from/project/root', :format => :json)

在您的Rabl模板中

object @any_name_you_like
attributes :id,:body
....

这会将您的模板呈现为json,并将指定的对象指定为其实例对象(您可以随意命名)

This will render your template as a json with the object specified as its instance object (you can name it anything you want)

这有点棘手.我发现的唯一选择是通过在调用范围内将所需对象设置为实例变量,并将此范围设置为呈现模板(请参见 scope ).

This is a bit more tricky. The only option I found is by setting the desired objects as instance variables in the calling scope and set this scope for the rendering of the template (see scope).

@one_object = ...
@another_object = ...
Rabl.render(nil, 'your_template', view_paths => 'relative/path/from/project/root', :format => :json, :scope => self)

在您的Rabl模板中

object @one_object
attributes :id,:body
node(:my_custom_node) { |m| @another_object.important_stuff }

这篇关于我如何通过rake任务将对象传递给rabl视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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