Skip to content

Instantly share code, notes, and snippets.

@danhodge
Last active June 7, 2021 14:22
Show Gist options
  • Save danhodge/bb0a1beabd56236b9e79a7c81dc38b68 to your computer and use it in GitHub Desktop.
Save danhodge/bb0a1beabd56236b9e79a7c81dc38b68 to your computer and use it in GitHub Desktop.
Rails Conditional Routing
# Conditional Routing in Rails
# Send requests matching the same path to different controller actions based on information in the request
# http://bjedrocha.com/rails/2015/03/18/role-based-routing-in-rails/
class ThingsConstraint
def initialize(*names)
@matches = names
end
def matches?(request)
user_name, _ = ActionController::HttpAuthentication::Basic.user_name_and_password(request)
@matches.include?(user_name)
end
end
# config/routes.rb
resources :things, :path => 'things', :only => [] do
member do
# routes to new_things#doit if the constraint evaluates to true
post :doit, constraints: ThingsConstraint.new('jane'), to: 'new_things#doit'
# routes to the original controller action if previous route did not match
post :doit
end
end
# Rails unhandled exception to error mappings are defined here:
Rails.configuration.action_dispatch.rescue_responses
# And processed via the ExceptionWrapper middleware
# https://github.com/rails/rails/blob/v5.1.6.1/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
# Stop spring
spring stop
# validates that field is present
validate :field, presence: true
# validates that field is not present
validate :field, absence: true
# Disable ActiveRecord Callbacks
# disables all *save callbacks on all ModelClass instances
ModelClass._save_callbacks.each do |cb|
ModelClass.skip_callback(cb.name, cb.kind, cb.filter)
end
# enables all *save callbacks on all ModelClass instances
ModelClass._save_callbacks.each do |cb|
ModelClass.set_callback(cb.name, cb.kind, cb.filter)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment