Skip to content

Instantly share code, notes, and snippets.

@wonderer007
Last active March 18, 2021 21:57
Show Gist options
  • Save wonderer007/7964d6dc2f5c04991d2455cf7ff4580a to your computer and use it in GitHub Desktop.
Save wonderer007/7964d6dc2f5c04991d2455cf7ff4580a to your computer and use it in GitHub Desktop.
Rails dynamic route
class EmployeeRouter
def initialize(&block)
@block = block || (-> { true })
end
def matches?(request)
employee = current_employee(request)
employee.present? && @block.call(employee)
end
def current_employee(request)
Employee.find_by(id: request.session[:employee_id])
end
end
require 'rails_helper'
RSpec.describe EmployeeRouter do
class MockHTTPRequest
def initialize(employee)
@employee = employee
end
def session
{ employee_id: @employee.id }
end
end
scenario 'For admin' do
admin = create(:admin, name: 'Jane Doe', access_code: '41315')
warehouse_employee = create(:warehouse_employee, name: 'Mike Hasmen', access_code: '14325')
support_agent = create(:support_agent, name: 'Agent Alin', access_code: '43876')
admin_request = MockHTTPRequest.new(admin)
warehouse_employee_request = MockHTTPRequest.new(warehouse_employee)
support_agent_request = MockHTTPRequest.new(support_agent)
admin_router = EmployeeRouter.new { |employee| employee.is_a?(Admin) }
warehouse_employee_router = EmployeeRouter.new { |employee| employee.is_a?(WarehouseEmployee) }
support_agent_router = EmployeeRouter.new { |employee| employee.is_a?(SupportAgent) }
expect(admin_router.matches?(admin_request)).to be(true)
expect(admin_router.matches?(warehouse_employee_request)).to be(false)
expect(admin_router.matches?(support_agent_request)).to be(false)
expect(warehouse_employee_router.matches?(warehouse_employee_request)).to be(true)
expect(warehouse_employee_router.matches?(admin_request)).to be(false)
expect(warehouse_employee_router.matches?(support_agent_request)).to be(false)
expect(support_agent_router.matches?(support_agent_request)).to be(true)
expect(support_agent_router.matches?(admin_request)).to be(false)
expect(support_agent_router.matches?(warehouse_employee_request)).to be(false)
end
end
Rails.application.routes.draw do
constraints(EmployeeRouter.new { |employee| employee.is_a?(Manager) }) do
get 'dashboard', to: 'managers#dashboard'
end
constraints(EmployeeRouter.new { |employee| employee.is_a?(Admin) }) do
get 'dashboard', to: 'admins#dashboard'
end
constraints(EmployeeRouter.new { |employee| employee.is_a?(SalesEmployee) }) do
get 'dashboard', to: 'sales_employees#dashboard'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment