Skip to content
This repository has been archived by the owner on Sep 30, 2018. It is now read-only.

Commit

Permalink
Add HistoryRouter for html5 routing
Browse files Browse the repository at this point in the history
  • Loading branch information
adambeynon committed Nov 29, 2013
1 parent 4a5e7d3 commit 9d8e9d1
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 1 deletion.
42 changes: 42 additions & 0 deletions opal/vienna/history_router.rb
@@ -0,0 +1,42 @@
module Vienna
class HistoryRouter
attr_reader :path, :routes

def initialize(&block)
@routes = []
@location = $global.location

Window.on(:popstate) { update }

instance_eval(&block) if block
end

def route(path, &handler)
route = Router::Route.new(path, &handler)
@routes << route
route
end

def update
path = if @location.pathname.empty?
'/'
else
@location.pathname
end

unless @path == path
@path = path
match @path
end
end

def match(path)
@routes.find { |r| r.match path }
end

def navigate(path)
`history.pushState(null, null, path)`
update
end
end
end
47 changes: 47 additions & 0 deletions spec/history_router_spec.rb
@@ -0,0 +1,47 @@
require 'spec_helper'
require 'vienna/history_router'

describe Vienna::HistoryRouter do
describe '#update' do
it 'updates path' do
subject.navigate('/foo')
expect(subject.path).to eq('/foo')
end

it 'calls #match with the new path' do
expect(subject).to receive('match').with('/new_url')
subject.navigate('/new_url')
end
end

describe '#route' do
it 'should add a new route' do
subject.route('/users') {}
expect(subject.routes.size).to eq(1)

subject.route('/hosts') {}
expect(subject.routes.size).to eq(2)
end
end

describe '#match' do
it 'returns nil when no routes on router' do
expect(subject.match('/foo')).to be_nil
end

it 'returns the matching route for the path' do
a = subject.route('/foo') {}
b = subject.route('/bar') {}

expect(subject.match('/foo')).to eq(a)
expect(subject.match('/bar')).to eq(b)
end

it 'returns nil when no matching route' do
subject.route('/foo') {}
subject.route('/bar') {}

expect(subject.match('/baz')).to be_nil
end
end
end
2 changes: 1 addition & 1 deletion vienna.gemspec
Expand Up @@ -21,6 +21,6 @@ Gem::Specification.new do |s|
s.add_dependency 'opal-jquery'
s.add_dependency 'opal-activesupport'

s.add_development_dependency 'opal-rspec', '~> 0.2.0'
s.add_development_dependency 'opal-rspec', '>= 0.2.1'
s.add_development_dependency 'rake'
end

0 comments on commit 9d8e9d1

Please sign in to comment.