public
Last active

  • Download Gist
FIRST
1
Here's an example refactoring from http://www.workingwithrails.com/forums/4-ask-a-rails-expert/topics/789-optimising-code
models.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Role < ActiveRecord::Base
ADMIN = 'admin'
 
belongs_to :user
belongs_to :building
 
named_scope :by, proc { |role|
{ :conditions => ['name = ?', role] }
}
end
 
class User < ActiveRecord::Base
has_many :roles
has_many :buildings, :through => :roles
end
new.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# The new way...
class Building < ActiveRecord::Base
has_many :roles
has_many :users, :through => :roles do
# Association extension
def with_role(name)
scoped(:conditions => ['roles.name = ? AND roles.id = ?', name, proxy_owner.id])
end
end
 
def find_admins_of
users.with_role(Role::ADMIN)
end
end
old.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11
# The old way...
class Building < ActiveRecord::Base
def find_admins_of
roles = self.roles
admins = []
for role in roles
admins << User.find(role.user_id) if role.role_type_id == Role::ADMIN
end
admins
end
end
test.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
require 'test/unit'
 
class AdminTest < Test::Unit::TestCase
def test_with_role_filters_by_role
# Create test objects
admin = User.create!
not_admin = User.create!
building = Building.create!
 
# Give the admin user the right role
admin.roles.create! :name => Role::ADMIN, :building => building
 
# Assert that the filter works
assert_equal [admin], building.users.with_role(Role::ADMIN)
 
# ...or if you prefer:
assert_equal [admin], building.find_admins_of
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.