The last few weeks of the semester were packed with new stuff, and I’ve been getting a bit behind on writing about it, so this post is going to be a long one.

Callbacks

A callback is a piece of code that is not run immediately, but is called later when a certain event occurs. The callback pattern is used in Rails to interact with ActiveRecord objects at different states in their life cycle. For example, before_save is a callback that lets you run an arbitrary piece of code before every object is created:

```ruby user.rb class User < ActiveRecord::Base before_save :set_default_balance

#This method will be run before every User is saved. def set_default_balance self.balance = 0 end end

<!-- more -->

### Javascript ###
Before teaching us anything about Javascript, Jeff explained that the purpose of learning it on top of Ruby and Rails is to make pages more dynamic. If you were to use just Ruby, Rails, HTML and CSS to develop your app, it would work just fine, but page content would only change when sending a new reqest and rendering a new page. With Javascript, you can change the HTML on a web page without sending a new request. 

Although there are many similarities between JavaScript and Ruby, there are some glaring differences. One of the biggest that stood out to me was how loop iteration is handled in each language. If I were to iterate over an array in Ruby, I could write something like this:

```ruby iteration.rb
array = [1,2,3,4,5]
    #each is an "Enumerator" built into Ruby to make iteration over collections easy.
array.each do |element|
  puts element * 2
end

A similar procedure in JavaScript:

```js iteration.js array = [1,2,3,4,5]

for(i = 0; i < array.length; ++i) { element = array[i] console.log(element * 2) }

JavaScript requires you to write a for loop for simple iteration. The first argument passed to the <code>for</code> is the index that the iteration should begin at. Since it is set to 0, it will start at the first element of the array. The second argument is a condition that must evaluate to <code>true</code> for the loop to keep iterating. In this case, the loop continues to iterate while the index is less than the length of the array. This is just a convoluted way of specifying that we want to iterate over the entire array. The third argument is the step value. <code>++i</code> means that we want to increment the index of the array by one each time the loop executes. Once you determine how the loop is going to work, you then have to specify what is the block variable on line 4, setting it equal to the index value for each pass through the loop. For me, this seemed pretty unintuitive compared to the Ruby implementation.

Luckily, some insanely smart people recognized that JavaScript wasn't the easiest of languages to work with and wrote a huge library called jQuery. jQuery is written in JavaScript, but makes it easy for developers to manipulate the DOM(Document Object Model) without having to get down in the minute details. If I wanted to insert text into a <code>div</code> with an id of <code>text</code> with pure JavaScript, I could do the following:

```js divs.js
  //Selects the element with an id 'text' and sets it equal to a variable 'div'
  var div = document.getElementById('text')
  
  div.innerHTML = "This is some text"

This is relatively straightforward, but it would get really cumbersome to keep setting variables and changing their content like this. jQuery makes it trivial to do this DOM manipulation.

```js jquery.js $(‘#text’).append(“This is some text”)


### AJAX ###
AJAX(Asynchronous Javascript and XML) is a client-side technique that allows JavaScript code to communicate with a server without leaving the current page. AJAX provides a method for exchanging data asynchronously between browser and server to avoid full page reloads. There's a pretty simple process to get basic AJAX functionality in a Rails app. Let's say you wanted to post a comment and have it appear on the page without refreshing. The following mark up is on the page:

```erb post.html.erb
<p>
  <%= post.content %>
</p>

<ul>
<% Comment.all.each do |comment| %>
  <li class="comment">
    <%= comment.text %>
  </li>
<% end %>
</ul>

<%= form_for Comment.new do |f| %>
  <%= f.text_field :text %>
<% end %>

:remote => true

To make any link or form submit an asychronous request, add :remote => true to the the options of the form_for:

```erb form_for <%= form_for Comment.new :remote => true do |f| <%= f.text_field :text %> <% end %>


#### respond_to ####
When making an ansynchronous request, the format header of the request is submitted as Javascript. By default, the controller handling the request will only respond to HTML formatted requests. To add handling for AJAX requests, you need to add a <code>respond_to</code> block. This block acts as a callback that tailors the data from your app depending on the format of the request. 
```ruby comments_controller.rb

class CommentsController < ApplicationController

  def create
   @comment = Comment.new
	  @comment.text = params[:text]
	
	if @comment.save
	  respond_to do |format|
	    format.html
		format.js
	  end
	else
	  respond_to do |format|
	    format.html do
		  render 'new'
		end
		format.js do
		  render { js: 'alert("Couldn't save comment.")
		  end
   	end
    end
  end
end

Now, your controller is wired up to handle AJAX requests. All that is left to do is write some JavaScript to be rendered.

JavaScript template

When you add the format.js line, Rails automatically looks for a JS template with the same name as the action, in this case, the create action. If you keep to the REST conventions, creat a template called create.js.erb. Like any ERB template, Ruby can be embedded into it, allowing you to manipulate Ruby data in Javascript.

```erb create.js.erb $(“ul”).append(<%= @comment.text %>)

Now, the JS code <code>create.js.erb</code> will be rendered whenever the create action in the comments controller is called, appending the comment to the list.

### Test Driven Development ###
Test driven development or TDD is a huge topic that I'm still very new to. It's an interesting and difficult habit/technique/culture to get used to. Test driven development is pretty much what it sounds like: the structure and content of your code is determined by tests. For someone new to TDD, it's natural to wonder what tests actually are. Tests are just pieces of code that invoke your application code without forcing you to manually test each part by hand. 

Ruby comes with it's own built-in testing framework, MiniTest, but a better alternative is Rspec. To install Rspec, just run <code>gem install rspec</code>. Here is an example of how you can test your Ruby code using Rspec:

```ruby model.rb
# This is the class we are going to test
class Model < ActiveRecord::Base
  def method
    0 
  end
end

```ruby model_spec.rb require ‘spec_helper’

describe “Model” do describe “#method” do it “should return 0” do x = Model.new expect(x.method).to eq(0) end end end

```

To run the spec, simply run rspec in your terminal when inside the project directory.

Why test? It seems like this would slow down the development process.

At first, testing your code definitely slows you down. You essentially write double the code you would if you just wrote application code. The real value of TDD isn’t in making the initial development process quick, it is in investing in the future cost of change of the product. Here’s a good graph to illustrate:

graph

So, if you want to quickly prototype an idea, TDD may not be the way to go. On the other hand, if you are starting development on a project that will eventually go into production, TDD is worth the time and effort.