
Originally Posted by
Darren884
optimizing the code in a controller to make it minimal
I not sure I'd call minimizing code the same as optimizing it. In my experience, optimal code is clear and concise code. Minimal code goes too far and is usually harder to debug and for others to work on.
However, the best way I've found to make clear and concise code in controllers is to follow DRY (Don't Repeat Yourself) principles. That is, identify items that are repeated in a number of methods and strip them out into a separate private method. For example:
This
Code:
def show
@search_data = some_search_information
@current_date = some_date
@item = params[:id]
#.... some other code ....
end
def edit
@search_data = some_search_information
@current_date = some_date
@item = params[:id]
#.... some other code ....
end
def update
#.... some code to process the update ....
if update_fails
@search_data = some_search_information
@current_date = some_date
@item = params[:id]
#.... some more code ....
end
end
Can be replaced with
Code:
def show
get_single_item_info
#.... some other code ....
end
def edit
get_single_item_info
#.... some other code ....
end
def update
#.... some code to process the update ....
if update_fails
get_single_item_info
#.... some more code ....
end
private
def get_single_item_info
@search_data = some_search_information
@current_date = some_date
@item = params[:id]
end
Also make sure you use meaningful names for thing. That way you can minimise comments and make debugging easier. For example:
Code:
#bad
a = Math.sqrt(b^2 + c^2)
#good
longest_side = Math.sqrt(shortest_side^2 + other_side^2)
Bookmarks