Class: Widget::Viewtroller

Inherits:
Object
  • Object
show all
Extended by:
Commandable
Defined in:
lib/widget/widget_viewtroller.rb

Instance Method Summary collapse

Constructor Details

#initializeViewtroller

You shouldn’t try to call initialize using Commandable because it creates a new class automatically for instance methods.

Think of the classes you let Commandable control as entry points to your app. Don’t try to have Commandable do a lot of class creation and manipulation of your application, just have the methods you call do all that.



11
12
13
# File 'lib/widget/widget_viewtroller.rb', line 11

def initialize
  @data = Data.instance
end

Instance Method Details

#destroy(name) ⇒ Object Also known as: delete



60
61
62
63
64
65
66
# File 'lib/widget/widget_viewtroller.rb', line 60

def destroy(name)
  if @data.delete(name)
    "#{name} destroyed. You heartless bastard!"
  else
    "There is no #{name} in storage."
  end
end

#listObject



50
51
52
53
54
55
56
57
# File 'lib/widget/widget_viewtroller.rb', line 50

def list
  puts "Widgets:"
  if @data.length > 0
    @data.read_all.collect{|widget| " #{widget[:name]}"}
  else
    " <none>"
  end
end

#new(name) ⇒ Object Also known as: add

The method name “new” makes sense here but notice it’s not the class.new method



17
18
19
20
21
22
23
# File 'lib/widget/widget_viewtroller.rb', line 17

def new(name)
  if @data.create(name)
    "You created widget #{name}"
  else
    "#{name} already exists!"
  end
end


39
40
41
# File 'lib/widget/widget_viewtroller.rb', line 39

def print_widgets(widgets)
  widgets.collect{|widget| " #{widget[:name]}: created: #{widget[:created_at]}; modified: #{widget[:modified_at]};"}
end

#resetObject



44
45
46
47
# File 'lib/widget/widget_viewtroller.rb', line 44

def reset
  @data.delete_all
  "All widgets destroyed. May they rest in peace."
end

#show(name = nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/widget/widget_viewtroller.rb', line 28

def show(name=nil)
  if name 
    widgets = @data.read(name)
    return "There is no #{name} in storage." if widgets.empty?
  else
    widgets = @data.read_all
    return "There are no widgets in storage." if widgets.empty?
  end
  print_widgets(widgets)
end

#upgrade(name) ⇒ Object



71
72
73
74
75
76
77
# File 'lib/widget/widget_viewtroller.rb', line 71

def upgrade(name)
  if @data.update(name) 
    "You just gave #{name} a fresh coat of paint!"
  else
    "There is no #{name} in storage."
  end
end