Skip to content

Commit

Permalink
Support setting parent_controller
Browse files Browse the repository at this point in the history
fixes #618
  • Loading branch information
jaynetics committed Jul 14, 2024
1 parent cafbfbf commit a156fb0
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,13 @@ class AccountsController < ApplicationController
end
```

By default, `InheritedResources::Base` will inherit from `::ApplicationController`. You can change this in a rails initializer:

```ruby
# config/initializers/inherited_resources.rb
InheritedResources.parent_controller = 'MyController'
```

## Overwriting defaults

Whenever you inherit from InheritedResources, several defaults are assumed.
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/inherited_resources/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module InheritedResources
# call <tt>default</tt> class method, call <<tt>actions</tt> class method
# or overwrite some helpers in the base_helpers.rb file.
#
class Base < ::ApplicationController
class Base < InheritedResources.parent_controller.constantize
# Overwrite inherit_resources to add specific InheritedResources behavior.
def self.inherit_resources(base)
base.class_eval do
Expand Down
4 changes: 4 additions & 0 deletions lib/inherited_resources.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ module InheritedResources
def self.flash_keys=(array)
Responders::FlashResponder.flash_keys = array
end

# Inherit from a different controller. This only has an effect if changed
# before InheritedResources::Base is loaded, e.g. in a rails initializer.
mattr_accessor(:parent_controller) { '::ApplicationController' }
end

ActiveSupport.on_load(:action_controller_base) do
Expand Down
19 changes: 19 additions & 0 deletions test/parent_controller_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
require 'test_helper'

def force_parent_controller(value)
InheritedResources.send(:remove_const, :Base)
InheritedResources.parent_controller = value
load File.join(__dir__, '..', 'app', 'controllers', 'inherited_resources', 'base.rb')
end

class ParentControllerTest < ActionController::TestCase
def test_setting_parent_controller
original_parent = InheritedResources::Base.superclass

assert_equal ApplicationController, original_parent
force_parent_controller('ActionController::Base')

assert_equal ActionController::Base, InheritedResources::Base.superclass
force_parent_controller(original_parent.to_s) # restore original parent
end
end

0 comments on commit a156fb0

Please sign in to comment.