HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Ruby: working with arrays

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
witharraysworkingruby

Problem

I am working on a script that collects all comments from my DB and inserts them into a hash. I then do a collect on the comments hash and split the comments into two separate comment hashes (vid_comments & wall_comments)

w_hash = Hash.new
    w_hash["comments"] = []
    contender.subscriber.videos.collect { |v| w_hash["comments"]  DATE_SUB( NOW(), INTERVAL 1 DAY)") }
    w_hash["comments"]  DATE_SUB( NOW(), INTERVAL 1 DAY)")
    w_hash["comments"].delete_if { |x| x.blank? }

    w_hash["vid_comments"] = w_hash["comments"].collect { |c| !c.media_id.nil? }
    w_hash["wall_comments"] = w_hash["comments"].collect { |w| w.parent_id == 0 }
    w_hash.delete("comments")


Is there anyway to shorten the code? I am pretty new to Ruby (PHP import) so excuse my ignorance in things I may be doing wrong.

Solution

well, first of all your first query is extremely ineffective

contender.subscriber.videos.collect { |v| w_hash["comments"]  DATE_SUB( NOW(), INTERVAL 1 DAY)") }


this will query you db for each video you've got

second, you really shouldn't duplicate you SQL queries, i propose that you add scope to your Comment model (you are using Rails 3, right?)

scope :recent, where("created_at > ?", 1.day.ago)


to make your queries more effective you should use .joins method of ActiveRecord

after all this you code would be something like that

comments = Comment.joins(:videos).where(:videos => { :subscriber => contender.subscriber }).recent
comments << contender.profile.comments.recent

w_hash = {}
w_hash["vid_comments"] = comments.collect { |c| !c.media_id.nil? }
w_hash["wall_comments"] = comments.collect { |c| c.parent_id == 0 }

Code Snippets

contender.subscriber.videos.collect { |v| w_hash["comments"] << v.comments.where("created_at > DATE_SUB( NOW(), INTERVAL 1 DAY)") }
scope :recent, where("created_at > ?", 1.day.ago)
comments = Comment.joins(:videos).where(:videos => { :subscriber => contender.subscriber }).recent
comments << contender.profile.comments.recent

w_hash = {}
w_hash["vid_comments"] = comments.collect { |c| !c.media_id.nil? }
w_hash["wall_comments"] = comments.collect { |c| c.parent_id == 0 }

Context

StackExchange Code Review Q#3987, answer score: 8

Revisions (0)

No revisions yet.