Namespace issue when generating actions that match the app name

If you generate an action with the same resource name as the app, you end up having to manually modify the generated files to prevent namespace issues.

e.g,

% hanami new books
% cd books
% bundle exec rspec

Then generate the action and run the tests to see the issue

% bin/hanami g action books.index
% bundle exec rspec

An error occurred while loading ./spec/actions/books/index_spec.rb.
Failure/Error:
  class Index < Books::Action
    def handle(request, response)
    end

NameError:
  uninitialized constant Books::Actions::Books::Action
# ./app/actions/books/index.rb:6:in '<module:Books>'
# ./app/actions/books/index.rb:5:in '<module:Actions>'
# ./app/actions/books/index.rb:4:in '<module:Books>'
# ./app/actions/books/index.rb:3:in '<top (required)>'
# ./spec/actions/books/index_spec.rb:3:in '<top (required)>'


Top 0 slowest examples (0 seconds, 0.0% of total time):

Finished in 0.00005 seconds (files took 0.79228 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples

The fix is simple:

git diff
diff --git a/app/actions/books/index.rb b/app/actions/books/index.rb
index fca1110..d48ffd0 100644
--- a/app/actions/books/index.rb
+++ b/app/actions/books/index.rb
@@ -3,7 +3,7 @@
 module Books
   module Actions
     module Books
-      class Index < Books::Action
+      class Index < ::Books::Action
         def handle(request, response)
         end
       end
diff --git a/app/views/books/index.rb b/app/views/books/index.rb
index 5b1037e..9f8db73 100644
--- a/app/views/books/index.rb
+++ b/app/views/books/index.rb
@@ -3,7 +3,7 @@
 module Books
   module Views
     module Books
-      class Index < Books::View
+      class Index < ::Books::View
       end
     end
   end

Seems like an easy fix to make in the generators to avoid this issue.

Great pickup, thank you for sharing it, @mddelk! Is a fix something you’d like to try building? If not, I’ll make sure we take care of it.

Is a fix something you’d like to try building?

yep, I’ll work a fix for this.

btw, thanks for hanami!

Thanks for taking that on!

A couple notes to help guide you:

  • We only want the leading :: when there’s a namespace conflict that would happen
  • We’ll want this for all our generators, not just Action. It could be done for action generator first to keep the PR small then expanded to other generators later (by you or someone else), or it may make sense to fix at a higher level that all generators can benefit from.