- What is one major concern of the following code and how would you
improve it?
class BookController < ApplicationController
def rename
@book = Books.find(params[:id])
if @book.update_attribute(:title, sanitize(params[:title]))
format.json { render json: { status: 200 } }
else
format.json { render json: { status: 500 } }
end
end
end
-
How would you optimize the following code?
def library_for_30_books
Books = library.limit(30)
Books.flat_map do |book|
book.pages.to_a
end
end
-
What flaw do you see in this code? How would you REFACTOR
it?
class BookController < ApplicationController
def index
@published_books = Books.where(‘published_at <= ?’, Time.now)
@unpublished_books = Books.where(‘ published_at = ? OR published_at >
?’, nil, Time.now)
end
end
-
Carefully analyze the below few segments of code. The
server
takes an total average of 1850ms to render this page. What strategies
would
you use to optimize the rendering time? (Hint: there’s more than 1
strategy
to be implemented)
Controller
def index
@themes = Theme.includes(:categories).published.order(created_at:
:desc) #
takes an average of 350ms
@featured_book = Books.includes(:categories).where(featured: true) #
takes
an average of 500ms
respond_to do |format|
format.html
format.json { render json: @themes }
end
end
View (part of it) - this portion takes an average of 1000ms to render
<% @themes.each do |theme| %>
<% if theme.is_new? %>
<i class="icon-tagnew"></i>
<% end %>
<% if theme.is_featured? %>
<i class="icon-tagfeatured"></i>
<% end %>
<div class="book-img">
<a href="#">
<%= image_tag(image_path('v4/b/loading.gif'), alt: 'Harry
Potter’,
class: ‘lazy pikto-loading-lg’, data: { original:
theme.snapshot.url(:medium) }) %>
</a>
</div>
<%= theme.try(:title) %>
<% end %>