Search code examples
hanami

How can I use the method (helper) defined in a view in another view?


Let's say I have a form defined in View

module Admin
  module Views
    module Dashboard
      class New
        include Admin::View

        def form
          form_for :link, routes.links_path do
            text_field :url
            submit 'Create'
          end
        end
...

Am I missing something? since example below doesn't work:

module Admin
  module Views
    module Dashboard
      class Index
        include Admin::View
        include Dashboard::New
...

Solution

  • You can't to share code from one view to another this way. Your snippet does not work because Ruby does not allow to include classes in to another classes. So, if you want to do this - you should to use helper module. For your case it should looks like this:

    module Admin
      module Helpers
        module Dashboard
          def form
            form_for :link, routes.links_path do
              text_field :url
              submit 'Create'
            end
          end
        end
      end
    end
    

    and include it in your view

    module Admin
      module Views
        module Dashboard
          class New
            include Admin::View
            include Admin::Helpers::Dashboard
    
            # ...
          end
        end
      end
    end
    

    or include it globally in your app

    # apps/admin/application.rb
    
    view.prepare do
      include Hanami::Helpers
      include Admin::Helpers::Dashboard
    end
    

    documentation: https://guides.hanamirb.org/helpers/custom-helpers/