Class: Milktea::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/milktea/model.rb

Overview

Base model class for creating TUI components following the Elm Architecture

Direct Known Subclasses

Container

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(state = {}) ⇒ Model



29
30
31
32
# File 'lib/milktea/model.rb', line 29

def initialize(state = {})
  @state = default_state.merge(state).freeze
  @children = build_children(@state)
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



8
9
10
# File 'lib/milktea/model.rb', line 8

def children
  @children
end

#stateObject (readonly)

Returns the value of attribute state.



8
9
10
# File 'lib/milktea/model.rb', line 8

def state
  @state
end

Class Method Details

.child(klass, mapper = nil) ⇒ Object

Define a child model with optional state mapping



14
15
16
17
18
19
20
# File 'lib/milktea/model.rb', line 14

def child(klass, mapper = nil)
  @children ||= []
  @children << {
    class: klass,
    mapper: mapper || ->(_state) { {} }
  }
end

.childrenArray<Hash>

Get all child definitions for this model



24
25
26
# File 'lib/milktea/model.rb', line 24

def children
  @children ||= []
end

Instance Method Details

#children_viewsString

Combine all children views into a single string



59
60
61
# File 'lib/milktea/model.rb', line 59

def children_views
  @children.map(&:view).join
end

#screen_heightInteger

Get the current screen height



71
72
73
# File 'lib/milktea/model.rb', line 71

def screen_height
  TTY::Screen.height
end

#screen_sizeArray<Integer>

Get the current screen size



77
78
79
# File 'lib/milktea/model.rb', line 77

def screen_size
  TTY::Screen.size
end

#screen_widthInteger

Get the current screen width



65
66
67
# File 'lib/milktea/model.rb', line 65

def screen_width
  TTY::Screen.width
end

#update(message) ⇒ Array(Model, Message)

Update the model based on a message

Raises:

  • (NotImplementedError)


43
44
45
# File 'lib/milktea/model.rb', line 43

def update(message)
  raise NotImplementedError, "#{self.class} must implement #update"
end

#viewString

Render the model to a string representation

Raises:

  • (NotImplementedError)


36
37
38
# File 'lib/milktea/model.rb', line 36

def view
  raise NotImplementedError, "#{self.class} must implement #view"
end

#with(new_state = {}) ⇒ Model

Create a new instance with updated state



50
51
52
53
54
55
# File 'lib/milktea/model.rb', line 50

def with(new_state = {})
  merged_state = @state.merge(new_state)
  return Kernel.const_get(self.class.name).new(merged_state) if self.class.name

  self.class.new(merged_state)
end