How can I pass an object to rabl views from rake task

吃可爱长大的小学妹 提交于 2020-01-14 02:46:26

问题


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

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

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.

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

index.json.rabl

@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

回答1:


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

  1. Pass a single object explicitly as a parameter
  2. Pass multiple objects implicitly by scope

By Parameter

In your task

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

In your Rabl Template

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

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

By 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).

In your task

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

In your Rabl Template

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


来源:https://stackoverflow.com/questions/10708046/how-can-i-pass-an-object-to-rabl-views-from-rake-task

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