简体   繁体   中英

Rails navigation bar the depends on user state and path

I am looking for a good pattern for having a navigation bar that depends on the users state and the current path.

In our application we have a navigation bar, which shows user specific options for logged in users (my profile, my jobs, ...etc) and guest specific options for guest users (How does it work, Become member, ...etc).

Now we also have a demo user, who should be shown the user specific options when he is on a subset of paths and the guest specific options when he is on different paths.

My current solution is a whitelist stored in an array and a function that checks if the current path is in the array.

ALLOWED_FOR_DEMO = ['profile', 'demo_jobs', 'jobs']

def allowed_for_demo?
  ALLOWED_FOR_DEMO.each { |path|
    return true if request.path.include? path
  }
  return false
end

This is then checked in the header view.

<% if allowed_for_demo? %>
  <div class="navbar">
    <div class="navbar-inner">
      <div class="container">
      </div>
    </div>
  </div>
<% end %>

The pattern for this is pretty bad if you ask me, so if anyone has a better pattern for this it would be very appreciated.

Still better you can try this. Atleast it will return as soon as it finds first element.

def allowed_for_demo?
  ALLOWED_FOR_DEMO.any? { |path|
    request.path.include? path
  }
end

Is ALLOWED_FOR_DEMO a global variable? If you put that in a helper, you the can define two methods, one for popultaing the array, and the other to check if its allowed for demo.

class AllowedDemoHelper
  def set_allowed_demo_path(path)
    @allowed_demo_path = path
  end

  def allowed_for_demo?
   (@allowed_demo_path || []).any? do |path|
     request.path.include? path
   end
  end
end

You could also put it in ApplicationController, but I think the helper approach is better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM