1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
Camping.goes :Nuts

module Nuts::Models
  class Page < Base
  end
  # Always place models before migrations
  class BasicFields < V 1.0
    def self.up
      create_table Page.table_name do |t|
        t.string :title
        t.text   :content
        # This gives us created_at and updated_at
        t.timestamps
      end
    end

    def self.down
      drop_table Page.table_name
    end
  end
end

module Nuts::Controllers

  class Pages < R '/'
    def get
      # Only fetch the titles of the pages.
      @pages = Page.all(:select => "title")
      render :list
    end
  end

  class PageX
    def get(title)
      if @page = Page.find_by_title(title)
        render :view
      else
        redirect PageXEdit, title
      end
    end

    def post(title)
      @page = Page.find_or_initialize_by_title(title)
      @page.content = @input.content
      @page.save
      redirect PageX, title
    end
  end

  class PageXEdit
    def get (title)
      @page = Page.find_or_initialize_by_title(title)
      render :edit
    end
  end
end

module Nuts::Views
  def list
    h1 "All pages"
    ul do
      @pages.each do |page|
        li do
          a page.title, :href => R(PageX, page.title)
        end
      end
    end
  end

  def view
    h1 @page.title
    self << @page.content
    p "updated: #{page.updated_at}"
    p "created: #{page.created_at}"
  end

  def edit
    h1 @page.title
    form :action => R(PageX, @page.title), :method => :post do
      textarea @page.content, :name => :content,
        :rows => 10, :cols => 50
      br
      input :type => :submit, :value => "Submit!"
    end
  end
end

def Nuts.create
  Nuts::Models.create_schema
end

# working example from the tutorial at:
# http://stuff.judofyr.net/camping-docs/book/02_getting_started.html

# to check results of the irb session from the tutorial on the database:
# cd to the directory containing camping.db (in your home dir)
# sqlite3 camping.db
# > .tables
# or just:
# > select * from nuts_pages;
# 1|Hiking|You can also set the values like this.|2009-11-01 18:26:34|2009-11-01 18:26:34
# 2|Fishing|Go fish!|2009-11-01 18:28:11|2009-11-01 18:28:11