2.4 Dropping self.

Before proceeding, let’s get something out of the way.

We are using the self keyword in our example because we are calling these methods on the Class (ApplicationController) that we are defining the action (play_rock) for. Recall when we learned about the Person Class, with the instance methods first_name and last_name. If we wanted a full_name method we called self.first_name + self.last_name.

In our example, we’re defining play_rock and we want use the method redirect that already exists on ApplicationController. We don’t see def redirect in our Class, since it’s inherited via < ActionController::Base and is defined there. So, we are using a method that already exists in the Class to build our new method, hence self.redirect_to.

But, in Ruby, when we call a method on self, we can drop the self., and Ruby will figure it out. Before anything, Ruby will look to see if that object exists in the Class, no self. required!

In practice, that means we can re-write the code to:

# config/routes.rb

get("/rock", { :controller => "application", :action => "play_rock" })

{: mark_lines=“3” }

and

# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  def play_rock
    redirect_to("https://www.wikipedia.org")
  end 
end

{: mark_lines=“5” }