Created
June 27, 2009 00:25
-
-
Save nakajima/136835 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Here's an example refactoring from http://www.workingwithrails.com/forums/4-ask-a-rails-expert/topics/789-optimising-code |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment