cells-rails icon indicating copy to clipboard operation
cells-rails copied to clipboard

how do i access main_app?

Open nir0 opened this issue 7 years ago • 7 comments

i've generated an engine, it uses standard layout with cells inside. menu cell renders namespaced (wrong) links, so i found i need to use main_app.profile_path sadly, cells don't know what is this, i've been trying to include Rails::Engine with no luck. what should i include to make main_app work?

nir0 avatar May 11 '17 11:05 nir0

:joy: Don't include anything, try Rails.main_app or whatever the API is. Can you post your solution here, please? :heart:

apotonick avatar May 11 '17 11:05 apotonick

thank you for quick reply!

class WelcomeCell < BaseCell
  def show
    render
  end

  def menu
    @menu_items = [
        { name: 'links.profile', url: Rails.main_app.profile_path },
        { name: 'links.users', url: Rails.main_app.users_path },
        { name: 'links.nodes', url: Rails.main_app.nodes_path },
        { name: 'links.companies', url: Rails.main_app.companies_path },
        { name: 'links.roles', url: Rails.main_app.roles_path }
    ]
    render
  end

end

error: undefined method 'main_app' for Rails:Module

if i replace Rails with Rails::Engine error changes to Rails::Engine is abstract, you cannot instantiate it directly.

nir0 avatar May 11 '17 11:05 nir0

Maybe our best @rafaelfranca can help here? :tropical_drink:

apotonick avatar May 11 '17 11:05 apotonick

include Rails.application.routes.mounted_helpers

makes main_app method accessible, but it doesn't work the way it meant: main_app.profile_path returns /tickets/profile instead of /profile

nir0 avatar May 11 '17 16:05 nir0

if i pass main_app from view and use it in cell, it works, but need to pass it to each cell, it's a dirty hack

nir0 avatar May 11 '17 16:05 nir0

Ha, you're wrong on this! It is super dirty and a hack the way Rails helpers do it and the way they're included into different classes and override each other. They are globals, and globals are not good.

What you have to do ATM is passing a dependency through a chain of objects. It's called a dependency injection and the way Rails should've dealt with such things in the first place. You can use the :context object to pass things to nested cells (almost a global but not a hack :joy: ).

apotonick avatar May 11 '17 18:05 apotonick

I've experienced this issue when I'v tried to use rich_text_area from activetext inside cell's view.

The solution was to pass main_app to the cell:

= cell(User::Cell::Form, @form, context: { main_app: main_app } ).(:settings)

and add following method inside cell class:

def main_app
   context[:main_app]
end

artur79 avatar Apr 16 '19 12:04 artur79