Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created December 15, 2015 03:10
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 jgaskins/6624fbb7c6d678439b8c to your computer and use it in GitHub Desktop.
Save jgaskins/6624fbb7c6d678439b8c to your computer and use it in GitHub Desktop.
Graceful degradation from pushState routing to fragment-based routing
class Router
def initialize
if `window.location.pushState === undefined`
@location = FragmentLocation.new
if !has_fragment?
@location.copy_path_to_fragment!
end
else
@location = PushStateLocation.new
if has_fragment?
@location.move_fragment_to_path!
end
end
end
end
class Location
def navigate_to path
raise NotImplementedError, 'You must use a subclass of `Location`'
end
end
class FragmentLocation < Location
def navigate_to path
%x{ window.location.hash = path }
end
def copy_path_to_fragment!
%x{ window.location.hash = window.location.pathname }
end
end
class PushStateLocation < Location
def navigate_to path
%x{ window.history.pushState({}}, '', path) }
end
def move_fragment_to_path!
%x{ window.history.replaceState({}, '', hash) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment