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

巧了我就是萌 提交于 2019-12-06 12:05:00

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