Jump to content

The ultimate community for Ruby on Rails developers.


Photo

How would you optimize this code, a'la Rails way


  • Please log in to reply
2 replies to this topic

#1 Rowel

Rowel

    Controller

  • Members
  • 109 posts

Posted 17 September 2013 - 02:18 AM

This code works... but feel it's not the Rails way and could be more efficient. 
 
How would you optimize this snippet?  especially the checking for @post.likes_count.nil?

How would you implement throttling? Somebody can click the LIKE button multiple times, and it would generate multiple emails to the original poster. Wouldn't want that.  

 

  def likepost
    # look for post by id
    @post = Post.find_by(id: params[:id])


    # TO DO: we need throttling here... in case user multiple clicks the LIKE button, and inundate 
    # original poster with multiple email notifications


    if @post 
      # if found, increment likes_count counter, then save
      if @post.likes_count.nil?
        @post.likes_count = 1 
      else
        @post.likes_count += 1
      end 
      @post.save 
      
      # TO DO: send email notification to original poster
      #
    end


    # update the html page via Ajax
    respond_to do |format|
      format.js
    end
  end 


#2 Rowel

Rowel

    Controller

  • Members
  • 109 posts

Posted 17 September 2013 - 02:27 AM

Never mind..... 

 

 

From this code: 

      if @post.likes_count.nil?
        @post.likes_count = 1 
      else
        @post.likes_count += 1
      end 
      @post.save 

to this: 

      @post.increment!(:likes_count)

Ruby is freaking awesome!!!! 


  • Ohm likes this

#3 katafrakt

katafrakt

    Signalman

  • Members
  • 16 posts
  • LocationKrak√≥w, PL

Posted 17 September 2013 - 12:30 PM

Actually increment! comes from ActiveRecord, not Ruby stdlib so it wouldn't be that awesome in non-AR frameworks ;)






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users