Skip to content

Instantly share code, notes, and snippets.

@kristopher
Last active December 20, 2015 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristopher/6097907 to your computer and use it in GitHub Desktop.
Save kristopher/6097907 to your computer and use it in GitHub Desktop.
class Page
def self.from(path, method)
env = Rack::MockRequest.env_for(path, method: method)
request = ActionDispatch::Request.new(env)
router = Journey::Router.new(Rails.application.routes.set, {
parameters_key: ActionDispatch::Routing::RouteSet::PARAMETERS_KEY,
request_class: ActionDispatch::Request
})
klass = nil
router.recognize(request) do |route, matches, params|
tokens = []
action_class = params[:action].to_s.camelcase
method_class = method.to_s.camelcase
format_class = (params[:format] || 'html').to_s.camelcase
route.path.spec.each_slice(3) do |segments|
tokens << segments.detect do |segment|
if segment.to_s.present?
!(segment.to_s =~ (/\/|^:|^\.$|^\(?\.?\:format/))
end
end.to_s.camelcase
end
tokens.select!(&:present?).each do |token|
if (klass || self).const_defined?(token, false)
klass = (klass || self).const_get(token, false)
end
end
if klass
[action_class, method_class, format_class].each do |constant|
if klass.const_defined?(constant, false)
klass = klass.const_get(constant, false)
else
break
end
end
end
end
klass || self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment