From 9afa74df42ee54e444c6f99227f069e52c1f566a Mon Sep 17 00:00:00 2001 From: Antonio Terceiro Date: Thu, 16 Dec 2010 11:41:27 -0300 Subject: [PATCH] Smarter way of sorting profiles randomly --- app/models/profile_list_block.rb | 8 ++++++-- lib/noosfero/sql.rb | 15 --------------- test/unit/profile_list_block_test.rb | 13 ++++++++++--- 3 files changed, 16 insertions(+), 20 deletions(-) delete mode 100644 lib/noosfero/sql.rb diff --git a/app/models/profile_list_block.rb b/app/models/profile_list_block.rb index b372e2d..a2224db 100644 --- a/app/models/profile_list_block.rb +++ b/app/models/profile_list_block.rb @@ -12,12 +12,16 @@ class ProfileListBlock < Block end def profile_list - random = Noosfero::SQL.random_function + random = randomizer profiles.visible.all(:limit => limit, :select => 'DISTINCT profiles.*, ' + random, :order => random) end def profile_count - profiles.visible.count + profiles.visible.count('DISTINCT(profiles.id)') + end + + def randomizer + @randomizer ||= "(profiles.id % #{rand(profile_count)})" end # the title of the block. Probably will be overriden in subclasses. diff --git a/lib/noosfero/sql.rb b/lib/noosfero/sql.rb deleted file mode 100644 index ca3585b..0000000 --- a/lib/noosfero/sql.rb +++ /dev/null @@ -1,15 +0,0 @@ -module Noosfero - module SQL - class << self - - def random_function() - default = 'random()' - adapter = ActiveRecord::Base.configurations[Rails.env]['adapter'] - { - 'mysql' => 'rand()' - }[adapter] || default - end - - end - end -end diff --git a/test/unit/profile_list_block_test.rb b/test/unit/profile_list_block_test.rb index 59b6a52..1eb8a39 100644 --- a/test/unit/profile_list_block_test.rb +++ b/test/unit/profile_list_block_test.rb @@ -141,13 +141,20 @@ class ProfileListBlockTest < Test::Unit::TestCase p2 = fast_create(Person, :environment_id => env.id) p3 = fast_create(Person, :environment_id => env.id) - # force the "random" function to be something we know - Noosfero::SQL.stubs(:random_function).returns('-id') - block = ProfileListBlock.new block.stubs(:owner).returns(env) + # force the "random" function to return something we know + block.stubs(:randomizer).returns('-id') + assert_equal [p3.id, p2.id, p1.id], block.profile_list.map(&:id) end + should 'randomize using modulo operator and random number' do + block = ProfileListBlock.new + block.expects(:profile_count).returns(10) + block.expects(:rand).with(10).returns(5) + assert_match /profiles.id % 5/, block.randomizer + end + end -- libgit2 0.21.2