Skip to content

Instantly share code, notes, and snippets.

@pazaricha
Forked from elado/slug_rack_app.rb
Last active August 29, 2015 14:28
Show Gist options
  • Save pazaricha/83cf3005842308c007a0 to your computer and use it in GitHub Desktop.
Save pazaricha/83cf3005842308c007a0 to your computer and use it in GitHub Desktop.
Rails conditional controller
# routes.rb (very bottom route):
match '*path' => SlugRackApp
# slug_rack_app.rb
class SlugRackApp
def self.call(env)
path = env["action_dispatch.request.path_parameters"][:path]
query_params = if env["QUERY_STRING"]
Rack::Utils.parse_nested_query(env["QUERY_STRING"]).with_indifferent_access
else
{}
end
# here you need to find the controller/action according to a condition (using data in params)
controller = ArticlesController
action = :show
# you can manipulate params and put it back on the env, Rails middlewares will convert it back to params in your controller
article = Article.find_by_slug(query_params[:slug])
query_params[:id] = article.id
env["QUERY_STRING"] = query_params.to_query
response = controller.action(action).call(env)
response
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment