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

json, rabl, ruby-on-rails-3

Solution

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

- Pass a single object explicitly as a parameter

- 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 }

Problem

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 ```

Original source