I wrote following module in Rails 3 to generate .json files using erb templates:
module TemplateGenerator
require "erb"
def generate_menu(website_id)
menu_template = open_and_read_template("lib/menu.json.erb")
@website.find(website_id)
@home_page = @website.pages.first
create_file(menu_template,"public/menu.json")
end
private
def open_and_read_template(file_path)
file = File.open(file_path, "rb")
file.read
end
def create_file(template,file_name)
erb = ERB.new( template )
File.open(file_name, 'w') do |f|
f.write erb.result(binding)
end
end
end
The erb file is:
{
"text": "Menu",
"items": [
{
"text": "<%= @home_page.title %>",
},
<%= render :partial => 'item', :collection => @home_page.children.sort_by{|c| c.sibling_order} %>
]
}
and I’m trying to display this recursive partial:
{
"text": <%= item.title %>,
<% if item.children? %>
"items": [
<%= render :partial => 'item', :collection => item.children.sort_by{|c| c.sibling_order} %>
]
<% end %>
},
My question is how can I get the render method to work in this instance when I call generate_menu during an action in my application? Is there a better, more ‘rails’ way to create files using an erb template?