Class: Plushie::Route

Inherits:
Object
  • Object
show all
Defined in:
lib/plushie/route.rb

Overview

Client-side routing for multi-view apps. Pure data structure maintaining a navigation stack of [path, params] entries.

The stack is last-in-first-out. +push+ adds a new entry on top; +pop+ removes the top entry (never pops the last one). +current+ and +params+ read from the top of the stack.

Examples:

route = Plushie::Route.new(:home)
route = Plushie::Route.push(route, :settings, tab: "general")
Plushie::Route.current(route)   #=> :settings
Plushie::Route.params(route)    #=> { tab: "general" }
route = Plushie::Route.pop(route)
Plushie::Route.current(route)   #=> :home

Defined Under Namespace

Classes: State

Class Method Summary collapse

Class Method Details

.can_go_back?(route) ⇒ Boolean

Returns true if there is more than one entry on the stack.

Parameters:

Returns:

  • (Boolean)


74
75
76
# File 'lib/plushie/route.rb', line 74

def self.can_go_back?(route)
  route.stack.length > 1
end

.current(route) ⇒ Object

Returns the current (top) path.

Parameters:

Returns:

  • (Object)


58
59
60
# File 'lib/plushie/route.rb', line 58

def self.current(route)
  route.stack.first[0]
end

.history(route) ⇒ Array

Returns a list of all paths in the stack, most recent first.

Parameters:

Returns:

  • (Array)


82
83
84
# File 'lib/plushie/route.rb', line 82

def self.history(route)
  route.stack.map(&:first)
end

.new(initial_path, **params) ⇒ State

Creates a new route with +initial_path+ at the bottom of the stack.

Parameters:

  • initial_path (Object)

    the root path

  • params (Hash)

    optional params for the root entry

Returns:



30
31
32
# File 'lib/plushie/route.rb', line 30

def self.new(initial_path, **params)
  State.new(stack: [[initial_path, params]].freeze)
end

.params(route) ⇒ Hash

Returns the params associated with the current (top) path.

Parameters:

Returns:

  • (Hash)


66
67
68
# File 'lib/plushie/route.rb', line 66

def self.params(route)
  route.stack.first[1]
end

.pop(route) ⇒ State

Pops the top entry from the stack. Returns the route unchanged if only one entry remains (the root is never popped).

Parameters:

Returns:



49
50
51
52
# File 'lib/plushie/route.rb', line 49

def self.pop(route)
  return route if route.stack.length <= 1
  route.with(stack: route.stack[1..].freeze)
end

.push(route, path, **params) ⇒ State

Pushes a new +path+ (with optional +params+) onto the navigation stack.

Parameters:

  • route (State)
  • path (Object)
  • params (Hash)

Returns:



40
41
42
# File 'lib/plushie/route.rb', line 40

def self.push(route, path, **params)
  route.with(stack: [[path, params], *route.stack].freeze)
end