lib/rails-canhaz/canhaz_permission.rb in rails-canhaz-1.0.5 vs lib/rails-canhaz/canhaz_permission.rb in rails-canhaz-1.0.6
- old
+ new
@@ -61,11 +61,44 @@
subjects.each do |subject|
# Get the ids of the objects that matched
matching = results.find_all { |result| result.csubject_id == subject.id}.collect { |c| c.cobject_id }
h[subject.id] = objects.find_all { |object| matching.include? object.id }
end
-
h
+ end
+
+ # Gets Permissions for a given object class, subject class, and permission name in an organized hash
+ #
+ # @param [Class] object The object class
+ # @param [Class] subject The subject class
+ # @param [String, Symbol] The name of the permission
+ def self.objects_and_subjects_from_permission(object, subject, permission)
+ raise CanHaz::Exceptions::NotACanHazObject unless object.include?(CanHaz::ModelExtensions::Object)
+ raise CanHaz::Exceptions::NotACanHazSubject unless subject.include?(CanHaz::ModelExtensions::Subject)
+
+ permissions = CanHazPermission.where(
+ :csubject_type => subject.to_s,
+ :cobject_type => object.to_s,
+ :permission_name => permission
+ )
+
+ permissions = yield(permissions) if block_given?
+
+ subjects = subject.find_all_by_id(permissions.collect(&:csubject_id)).inject({}) { |res, cur| res[cur.id] = cur; res} # Map by id for better access
+ objects = object.find_all_by_id(permissions.collect(&:cobject_id)).inject({}) { |res, cur| res[cur.id] = cur; res} # Map by id for better access
+
+ result = []
+
+ permissions.each do |permission|
+ found = result.find { |row| row[:subject] == subjects[permission.csubject_id]}
+ if found
+ found[:objects].push objects[permission.cobject_id]
+ else
+ result.push({:subject => subjects[permission.csubject_id], :objects => [objects[permission.cobject_id]]})
+ end
+ end
+
+ result
end
end