Skip to content

Commit

Permalink
Resource class priority system for namespaced controllers
Browse files Browse the repository at this point in the history
Implemented a resource class priority system for namespaced
controllers, for instance if you got a controller called:
  Admin::GroupController

First priority for the resource will be the namespaced
model, i.e.:
  Admin::Group

Second priority for the resource is the camelcased model,
i.e.:
  AdminGroup

Otherwise it will use the controller's name, or fail with
a TypeError, i.e.:
  Group
  • Loading branch information
sirupsen committed Jan 14, 2011
1 parent 903d1e4 commit 8e5732a
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/inherited_resources/class_methods.rb
Expand Up @@ -255,7 +255,21 @@ def acts_as_shallow! #:nodoc:
#
def initialize_resources_class_accessors! #:nodoc:
# Initialize resource class

# First priority is the namespaced modek, e.g. User::Group
self.resource_class = begin
namespaced_class = self.name.sub(/Controller/, '').singularize
namespaced_class.constantize
rescue NameError; nil end

# Second priority the camelcased c, i.e. UserGroup
self.resource_class ||= begin
camelcased_class = self.name.sub(/Controller/, '').gsub('::', '').singularize
camelcased_class.constantize
rescue NameError; nil end

# Otherwise use the Group class, or fail
self.resource_class ||= begin
class_name = self.controller_name.classify
class_name.constantize
rescue NameError => e
Expand Down
34 changes: 34 additions & 0 deletions test/defaults_test.rb
Expand Up @@ -140,3 +140,37 @@ def mock_professor(stubs={})
end
end

class Group
end
class AdminGroup
end
module Admin; end
class Admin::Group
end
class Admin::GroupsController < InheritedResources::Base
end
class NamespacedModelForNamespacedController < ActionController::TestCase
tests Admin::GroupsController

def test_that_it_picked_the_namespaced_model
# make public so we can test it
Admin::GroupsController.send(:public, *Admin::GroupsController.protected_instance_methods)
assert_equal Admin::Group, @controller.resource_class
end
end

class Role
end
class AdminRole
end
class Admin::RolesController < InheritedResources::Base
end
class TwoPartNameModelForNamespacedController < ActionController::TestCase
tests Admin::RolesController

def test_that_it_picked_the_camelcased_model
# make public so we can test it
Admin::RolesController.send(:public, *Admin::RolesController.protected_instance_methods)
assert_equal AdminRole, @controller.resource_class
end
end

0 comments on commit 8e5732a

Please sign in to comment.