Skip to content

Instantly share code, notes, and snippets.

@bsodmike
Created October 28, 2011 18:18
Show Gist options
  • Save bsodmike/1322962 to your computer and use it in GitHub Desktop.
Save bsodmike/1322962 to your computer and use it in GitHub Desktop.
Render 404 via catch-all route in Rails 3.1
class CmsPageNotFound < StandardError; end
class PublicController < ApplicationController
rescue_from CmsPageNotFound do
render 'not_found', :status => :not_found and return false
end
def index
end
def show
@content_item = parse_path(params[:path])
raise CmsPageNotFound unless @content_item
end
private
def parse_path(path_parts)
# item = nil
# path = path_parts.split("/")
# if path.size == 1
# %w().include?path[0] ? item = true : item = false
# elsif path.size >= 2
# end
# item
nil
end
end
match "*path" => 'public#show'
@smostovoy
Copy link

are you sure it works with rails 3.1? looks like such route doesn't work in latest version

@bsodmike
Copy link
Author

bsodmike commented Dec 7, 2011

I've got a couple 3.1 projects implementing the above, and they are working fine so far. I believe the 'catch-all' was removed from the generated app template, but you can still certainly use it. Make sure it's the last route in your routes file though.

@bsodmike
Copy link
Author

Just added this to a new 3.1.3 app and it works great =)

@dimarski
Copy link

dimarski commented Feb 7, 2012

Nice :)

@bsodmike
Copy link
Author

bsodmike commented Feb 7, 2012

Thanks!

@SabretWoW
Copy link

@smostovoy: If this was SO, I'd definitely give you an upvote. Thanks for the nice simple solution!

And FYI, I'm running Rails 3.2.13 with Ruby 1.9.3-p392.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment