Ruby Rand Range
I assumed that rand would take a range as an argument. Something like rand(10..20), generating a random number between 10 and 20. Seems like you’d do this fairly often when working with random numbers and therefore, included. However, it doesn’t work. But the solution is almost as easy.
10 + rand(11) #=> produces a random number between 10 and 20
Since rand starts at 0 (like array indexes), we need to add an extra 1 to get what we’re expecting.
Ruby on Rails: activtiy stream Facebook newsfeed polymorphic associations simple
by bseanvt
1 comment
Simple Activity Stream Implementation in Rails
There are many ways to tackle the Facebook style activity stream feature for your app. The simplest approach, which you can tack on at almost any moment, is what I’ll describe here. You don’t have to create a new model for news feed items or create any polymorphic associations. You simply query for the records on separate models you would like aggregated in the stream, and render a partial for that record, which Rails will map for you.
# in app/controllers/home_controller.rb
def index
@activity_stream = (Forum.find(:all, :limit => 10, :conditions=>["created_at > ?", 1.day.ago]) + ForumPost.find(:all, :limit => 10)).sort_by {|item| - item.created_at.to_i}
end
The sort_by method at the end places all of your feed item into descending chronological order. Omit the minus sign and they will be sorted in ascending order.
sort_by {|item| - item.created_at.to_i} # in descending chronological order
Show your latest activity in your views…
#app/views/home/index.html.erb <%= render @activity_stream rescue nil %>
This assumes that you will have created the partials for each resource using Rails conventions i.e., you have in created the partials for the models like so app/views/_[the model name].html.erb. In this instance, you should have app/views/forums/_forum.html.erb and app/views/forum_posts/_forum_post.html.erb
You can rename the partials to something like _stream_forum.html.erb, if you already have the forum partial gainfully employed. You’ll need to change the view and prob. throw it into a loop to either check for a condition or use _stream_[model name].html.erb as the convention for any stream items.


