Simplify avatar lookup class

This commit is contained in:
Stephan Kaag 2013-07-12 23:07:54 +02:00
parent a43ed88699
commit 9c243aa9ce
2 changed files with 7 additions and 64 deletions

View File

@ -1,24 +1,19 @@
class AvatarLookup
attr_accessor :user_ids, :users
def initialize(user_ids=[])
self.user_ids = AvatarLookup.filtered_users(user_ids)
@user_ids = user_ids.tap(&:compact!).tap(&:uniq!)
end
# Lookup a user by id
def [](user_id)
self.users = AvatarLookup.hashed_users(user_ids) if self.users.nil?
self.users[user_id]
users[user_id]
end
private
def self.filtered_users(user_ids=[])
user_ids.flatten.tap(&:compact!).tap(&:uniq!)
end
def self.hashed_users(user_ids=[])
users = User.where(:id => user_ids).select([:id, :email, :username])
users_with_ids = users.collect {|x| [x.id, x] }.flatten
Hash[*users_with_ids]
def users
@users ||= User.where(:id => @user_ids).select([:id, :email, :username]).inject({}) do |hash, user|
hash.merge({user.id => user})
end
end
end

View File

@ -5,26 +5,10 @@ require_dependency 'avatar_lookup'
describe AvatarLookup do
let!(:user){ Fabricate(:user) }
user_ids = [1, 2]
describe '#new' do
before do
AvatarLookup.stubs(:filtered_users).once.returns(user_ids)
@avatar_lookup = AvatarLookup.new
end
it 'init with cleaned user ids' do
@avatar_lookup.user_ids.should eq(user_ids)
end
it 'init users hash' do
@avatar_lookup.users.should eq(nil)
end
end
describe '#[]' do
before do
@avatar_lookup = AvatarLookup.new([user.id])
@avatar_lookup = AvatarLookup.new([user.id, nil])
end
it 'returns nil if user_id does not exists' do
@ -39,40 +23,4 @@ describe AvatarLookup do
@avatar_lookup[user.id].should eq(user)
end
end
describe '.filtered_users' do
it 'returns empty array if no params' do
AvatarLookup.filtered_users.should eq([])
end
it 'returns empty array' do
AvatarLookup.filtered_users([]).should eq([])
end
it 'returns filtered ids' do
AvatarLookup.filtered_users(user_ids).should eq(user_ids)
end
it 'returns flatten filtered ids' do
AvatarLookup.filtered_users([1, [2]]).should eq(user_ids)
end
it 'returns compact filtered ids' do
AvatarLookup.filtered_users([1, 2, nil]).should eq(user_ids)
end
it 'returns uniq filtered ids' do
AvatarLookup.filtered_users([1, 2, 2]).should eq(user_ids)
end
end
describe '.hashed_users' do
it 'returns empty hash if no params' do
AvatarLookup.hashed_users.should eq({})
end
it 'returns hashed users by id' do
AvatarLookup.hashed_users([user.id]).should eq({user.id => user})
end
end
end