How to access app-settings from slice?

Hey :wave:,
I read following in the docs:

Every slice having automatic access to the app’s "settings" component is convenient, but for large apps this may lead to those settings becoming unwieldy: the list of settings can become long, and many settings will not be relevant to large portions of your app.

It says that you automatically have access to the app settings from the slice, but this is not the case, when the slice itself has settings. In my case I have slice settings and app settings and I want to access the app-settings from a slice.

What’s the best way to achieve this?

Thanks

I solved this issue by adding a merge interface.

class Hanami::Settings
  def self.merge(other) = settings.each { other.settings << _1 }
end
module Admin
  class Settings < Hanami::Settings
    Bookshelf::Settings.merge(self)
  end
end

Note that this loads the values separately from ENV, so don’t mutate your settings values.

@alassek has a great solution above! Thanks for sharing this!

Another option you might consider is explicitly importing the settings from the app into your slice. Make a slice config file like config/slices/my_slice.rb, and then add the following:

module MySlice
  class Slice < Hanami::Slice
    import keys: "settings", from: Hanami.app.container, as: "app"
  end
end

This should make the app’s settings available via MySlice::Slice["app.settings"], or via include Deps["app.settings"] in classes within that slice.

Side note: I realise that import statement isn’t particularly great compared to importing from other slices, where you can just use symbolic names, e.g. import from: :slice_name. I’d like to make from: :app work, possibly, or something else a bit nicer than the snippet above. That’s a task for the future, though :slight_smile:

2 Likes