1. 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

 

2.            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

 

3.            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

 

4.            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| %>

 <li id=”theme-item-<%= theme.id %>" class="theme-items">

   <div class="the-book <%= theme.pro? && current_user.is_free? ? 
'pro-template' : '' %>">

     <% 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>

   </div>

 

   <div class="book-details">

     <%= theme.try(:title) %>

   </div>

 </li>

<% end %>

 

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/1f178432-e5d3-4e1d-bc6a-62bacbdb073c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to