Translating Ruby to Javascript

While going through this Ruby on Rails Getting Started guide, I ran into a code example that felt really strange and hard to parse. (I think that I might be addicted to braces (and parentheses).)

def index
  @posts = Post.all
  respond_to do |format|
    format.html  # index.html.erb
    format.json  { render :json => @posts }

The purpose of the code is fairly clear, but in order to parse how it works I spent the night reading up on Ruby syntax (thanks Codecademy!). Here I’ve made a loose translation of the above Ruby code into JavaScript using my newfound knowledge. Maybe it will be useful to someone else coming upon Ruby for the first time.

function index() {
	posts = Post.all();
	respond_to(function(format) {
		format.html(); // index.html.erb
		format.json(function() {
			render({ "json": posts });

I’m choosing to ignore that index is part of a class in the original and that @posts is an instance variable in said class (and respond_to and render are inherited methods). I think it conveys the general idea well enough without opening up the can of worms that is JavaScript inheritance.

Leave a Reply

Your email address will not be published. Required fields are marked *