NetWorkOut: an exercise in rails

Lifting rails controllers to a higher level

NetWorkOut

NetWorkOut is a web app that I developed to expand my rails coding ability while studying with the Flatiron School. I built a database of muscles and exercises, from which users can build workouts. They can also view those that others have built and star them as favourites for future reference when training.

Setting Objects

One thing you will be familiar with if you have developed web apps is assigning instance variables from ids that are being passed through as parameters.

@object = ObjectClass.find(params[:id])
def set_object    if params[:id]        object = _prefixes[0].singularize        instance = object.capitalize.constantize.find(params[:id])        instance_variable_set("@#{object}", instance)    endend

Getting Objects

Building off the previous method to set objects in controllers, I wrote another method .get_object, again in the ApplicationController as shown:

def get_object    if params[:id]        object = _prefixes[0].singularize        instance_variable_get("@#{object}")    endend

Editing Permissions

With objects set, and able to be dynamically retrieved, I wanted a method that would verify whether a user had permission to edit an object regardless of its class.

  • a user can edit any object that belongs to them, and
  • an admin can edit anything.
def permission_to_edit?(object)    if object.class == User        object == current_user || admin?    else        object.try(:user_id) == current_user.id || admin?    endend

Permitted next step

With the prior method in place, its first deployment was to be used to guard actions where objects could be edited, and functions nicely with the .get_object method.

def permitted?    get_object ? permission_to_edit?(get_object) : trueend

Putting it all together

The .permitted? method was the missing piece of the puzzle needed for my next method .redirect_if_not_permitted.

def redirect_if_not_permitted     if !admin?        if request.method != "GET"            redirect_to_root unless logged_in? && permitted?        elsif action_name == "edit"            page_not_found unless logged_in? && permitted?         elsif action_name == "new"            page_not_found unless logged_in?         end    endend
  • secondly, were not permitted.

Session over!

I hope this post has helped you by introducing you to a number of new controller methods that I have found extremely satisfying, and that you could adapt to use in your own rails projects.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store