Hello,

Currently, in our project, we've migrated away from using Rake tasks and 
trying to use Rails Command classes instead.

However, one of the thing we started to notice is that we have to add our 
application's lib directory to $LOAD_PATH in order for Rails to find the 
custom commands.

As I look into the source code, I noticed that Rails have a really specific 
rule on where to find additional commands:

https://github.com/rails/rails/blob/5371d5dcf26f5a5321471517531f36defa114e68/railties/lib/rails/command/behavior.rb#L55-L65
          # This will try to load any command in the load path to show in 
help.
          def lookup!
            $LOAD_PATH.each do |base|
              Dir[File.join(base, *file_lookup_paths)].each do |path|
                path = path.sub("#{base}/", "")
                require path
              rescue Exception
                # No problem
              end
            end
          end

https://github.com/rails/rails/blob/5371d5dcf26f5a5321471517531f36defa114e68/railties/lib/rails/command.rb#L104-L110
        def lookup_paths # :doc:
          @lookup_paths ||= %w( rails/commands commands )
        end


        def file_lookup_paths # :doc:
          @file_lookup_paths ||= [ "{#{lookup_paths.join(',')}}", "**", 
"*_command.rb" ]
        end

Basically, Ralis will only loop through every rails/commands or commands 
within the $LOAD_PATH. While this work perfectly for gems (as they can just 
have lib/rails/commands and everything will just work™) it might lead into 
a weird directory structure when you try to implement a custom command 
within the application itself, and generally I believe there's a reason we 
don't have our application's lib directory in the $LOAD_PATH by default 
makes me feel wrong to add it back again.

So, I would like to propose a standard, well-documented path for custom 
command within the Rails application. Some candidates are:

   - app/commands — (This might not work well due to everything in app/ is 
   autoloadable by zeitwerk)
   - lib/commands — (Goes along with lib/tasks, so might be a good choice)
   - config/commands — (A bit weird since this isn't really a config)

Do you think we should add one of these example to Rails lookup path? I'll 
be willing to submit a PR to get it work.

Thank you,
Prem

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-core/3d028cb9-128d-44f2-9880-21fdc6151ba9%40googlegroups.com.

Reply via email to