Created
September 17, 2009 21:29
-
-
Save maxim/188734 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
context "with associations" do | |
setup do | |
fake_association = Struct.new(:macro, :name, :object) | |
fake_object_with_associations = Struct.new(:associations) do | |
def reflect_on_all_associations | |
associations | |
end | |
def method_missing(meth, *args, &blk) | |
association = associations.find{|a| a.name == meth} | |
association && association.object | |
end | |
def respond_to?(meth) | |
associations.find{|a| a.name == meth} | |
end | |
end | |
associations = [] | |
associations << fake_association.new(:belongs_to, :user, @instance) | |
@post = fake_object_with_associations.new(associations) | |
end | |
should "have has_role? method using association if association exists" do | |
assert @instance.has_role?(:user, @post) | |
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
def has_role?(role, object = nil) | |
is_active_record_object = object.class.respond_to?(:reflect_on_all_associations) | |
role = role.to_s | |
plural_role = role.pluralize | |
if is_active_record_object | |
associations = Hash[*object.class.reflect_on_all_associations.map{|a| [a.name, a.macro]}.flatten] | |
match_association = associations.keys.find{|a| a == role.to_sym || a == plural_role.to_sym} | |
match_association_type = associations[match_association] | |
end | |
if is_active_record_object && match_association | |
case match_association_type | |
when :has_many, :has_and_belongs_to_many | |
begin | |
!!object.respond_to?(plural_role) && object.send(plural_role).find(self.id) | |
rescue ActiveRecord::RecordNotFound | |
false | |
end | |
else | |
object.respond_to?(role) && object.send(role) && object.send(role).id == self.id | |
end | |
else | |
self.send("#{role}?") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment