Have a look at the top_topic.rb file
top_topic.rb
https://github.com/discourse/discourse/blob/master/app/models/top_topic.rb#L143-L192