How to achieve slice lib directory autoloading?

Hey,

if I want the same lib-directory autoloading feature for a slice, as described here for the root, I have to configure it manually at slice container. Am I right?

Furthermore: Do you recommend placing structs under slices/my_slice/structs/... and opting out from autoregistration via…

module MySlice
  class Slice < Hanami::Slice
    config.no_auto_register_paths << "structs"
  end
end

…or is it better to place structs in the lib-directory slices/my_slice/lib/structs
I think the placing them under slices/my_slice/structs/... makes more sense.

thanks and best regards

Hi @wuarmin! Thanks for your question :slight_smile:

All slice directories are configured for autoloading, so any classes you define there will be accessible by their constants.

If you want classes defined in your slice directory not to be auto-registered in the container, then yes, you should add them to the no_auto_register_paths like you’ve showed:

module MySlice
  class Slice < Hanami::Slice
    config.no_auto_register_paths << "structs"
  end
end

By default, our no_auto_register_paths contains ["entities"].

Another option for you here would be to put this config in config/app.rb so it can apply to every slice:

module MyApp
  class App < Hanami::App
    config.not_auto_register_paths += ["structs"]
  end
end

And if you want to opt out specific individual files from being auto-registered, you can also add the # auto_register: false magic comment to the top of those files.

As for where you should put your struct classes, I think putting them directly in the root of the slice would be preferable :+1:

Our special handling of lib/ under slice directories (i.e. configuring the autoloader and the container to expect files under slices/some_slice/lib/ to define classes in the slice namespace) is not a publicised feature right now, and we reserve the right to change it. (For example, I could possibly see there being merit in excluding a slice’s lib/ directory from auto-registration entirely, allowing it to serve as a single place for holding any classes that should be referenced directly rather than through the container. Or to go in another direction, given that right now the slice lib/ directory offers nothing over just putting the files in the slice root, we could just drop it entirely, to eliminate this as a source of confusion for users. At this point I’d be inclined to do the latter).

1 Like

@timriley would you mind elaborating, how do you judge, which class is preferred to be used via container, and which not?