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

Commit 9d8e9d1

Browse files
committedNov 29, 2013
Add HistoryRouter for html5 routing
1 parent 4a5e7d3 commit 9d8e9d1

File tree

3 files changed

+90
-1
lines changed

3 files changed

+90
-1
lines changed
 

Diff for: ‎opal/vienna/history_router.rb

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
module Vienna
2+
class HistoryRouter
3+
attr_reader :path, :routes
4+
5+
def initialize(&block)
6+
@routes = []
7+
@location = $global.location
8+
9+
Window.on(:popstate) { update }
10+
11+
instance_eval(&block) if block
12+
end
13+
14+
def route(path, &handler)
15+
route = Router::Route.new(path, &handler)
16+
@routes << route
17+
route
18+
end
19+
20+
def update
21+
path = if @location.pathname.empty?
22+
'/'
23+
else
24+
@location.pathname
25+
end
26+
27+
unless @path == path
28+
@path = path
29+
match @path
30+
end
31+
end
32+
33+
def match(path)
34+
@routes.find { |r| r.match path }
35+
end
36+
37+
def navigate(path)
38+
`history.pushState(null, null, path)`
39+
update
40+
end
41+
end
42+
end

Diff for: ‎spec/history_router_spec.rb

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
require 'spec_helper'
2+
require 'vienna/history_router'
3+
4+
describe Vienna::HistoryRouter do
5+
describe '#update' do
6+
it 'updates path' do
7+
subject.navigate('/foo')
8+
expect(subject.path).to eq('/foo')
9+
end
10+
11+
it 'calls #match with the new path' do
12+
expect(subject).to receive('match').with('/new_url')
13+
subject.navigate('/new_url')
14+
end
15+
end
16+
17+
describe '#route' do
18+
it 'should add a new route' do
19+
subject.route('/users') {}
20+
expect(subject.routes.size).to eq(1)
21+
22+
subject.route('/hosts') {}
23+
expect(subject.routes.size).to eq(2)
24+
end
25+
end
26+
27+
describe '#match' do
28+
it 'returns nil when no routes on router' do
29+
expect(subject.match('/foo')).to be_nil
30+
end
31+
32+
it 'returns the matching route for the path' do
33+
a = subject.route('/foo') {}
34+
b = subject.route('/bar') {}
35+
36+
expect(subject.match('/foo')).to eq(a)
37+
expect(subject.match('/bar')).to eq(b)
38+
end
39+
40+
it 'returns nil when no matching route' do
41+
subject.route('/foo') {}
42+
subject.route('/bar') {}
43+
44+
expect(subject.match('/baz')).to be_nil
45+
end
46+
end
47+
end

Diff for: ‎vienna.gemspec

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,6 @@ Gem::Specification.new do |s|
2121
s.add_dependency 'opal-jquery'
2222
s.add_dependency 'opal-activesupport'
2323

24-
s.add_development_dependency 'opal-rspec', '~> 0.2.0'
24+
s.add_development_dependency 'opal-rspec', '>= 0.2.1'
2525
s.add_development_dependency 'rake'
2626
end

0 commit comments

Comments
 (0)