How the Helper Methods in Sinatra Helped Me Made My App DRY

Kamille Longalong
2 min readSep 7, 2020
Image by Goumbik from Pixabay

DRY — Don’t Repeat Yourself.

The purpose of this principle is to cut down on the repetition of codes.

When you start creating your application, you will notice that you keep on using the same code over and over again on different methods. This is where the helper methods come in.

Helper methods are codes you write that you can use so you don’t have to write repetitive codes. When I was doing my Sinatra project, I used two helper methods that helped me keep my code DRY.

From what I know now, there are two ways to use helper methods: create a helper.rb in the models directory and write the methods under a Helper class or add the methods in the applicationcontroller.rb in the controllers directory.

I will only talk about what I used in my project — I added the methods in my Application Controller.

The two helper methods that I used are logged_in? (checks if there is a user who is logged in) and current_user (verifies who the current user is).

This is what it looks like in my Application Controller:

helpers do  def logged_in?
!!current_user
end
def current_user
@user = User.find_by_id(session[:user_id])
end
end

Since these helper methods are inside the Application Controller as instance methods, I can just call them inside a method without having to pass an argument.

I hope this helps.

--

--