Last active
August 29, 2015 14:23
-
-
Save elado/5b9b6aa9460b43dd86d4 to your computer and use it in GitHub Desktop.
Rails conditional controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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