Class: Milksteak::Cms

Inherits:
Object
  • Object
show all
Defined in:
lib/milksteak/cms.rb

Constant Summary collapse

@@pages =
[]
@@routes =
nil

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Cms

Returns a new instance of Cms.



6
7
8
# File 'lib/milksteak/cms.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#_call(env) ⇒ Object



72
73
74
75
76
77
78
79
80
81
# File 'lib/milksteak/cms.rb', line 72

def _call(env)
  if match = route(env["PATH_INFO"]) and match[:page]
puts match.inspect
    @response = [match[:page].render]
    [200, {"Content-Type" => "text/html", "Content-Length" => @response[0].bytesize.to_s}, @response]
  else    
    @status, @headers, @response = @app.call(env)
    [@status, @headers, @response]
  end
end

#call(env) ⇒ Object



10
11
12
# File 'lib/milksteak/cms.rb', line 10

def call(env)
  dup._call(env)
end

#load_pagesObject



14
15
16
17
18
19
20
21
22
# File 'lib/milksteak/cms.rb', line 14

def load_pages
  puts "LOADING PAGES"
  @@pages = []
  Milksteak::Page.list.each do |name|
    name = name.match(/^.+\/(.+)\.yml/)[1]
    page = Milksteak::Page.load(name, "r")
    @@pages << page
  end
end

#route(url) ⇒ Object



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
# File 'lib/milksteak/cms.rb', line 37

def route(url)
  # search primary first, then dynamic
  routes[:dynamic].sort { |a,b| b.length <=> a.length }.each do |route|
    if tmp = url.match(route.pattern)
      keys = route.page.data["route"].split("/").reject{|x| x[0] != ":"}
      params = {}
      # our match data includes the original string, so compare against 
      # its length minus that position
      if keys.length == tmp.length-1
        keys.each_with_index do |k,i| 
          k = k.gsub(/^\:/, "")
          # our arrays are off-by-one because of the case above
          params[k] = tmp[i+1]
        end
      end
      return { :page => route.page, :params => params }
    end
  end
  routes[:primary].sort { |a,b| b.length <=> a.length }.each do |route|
    if url.match(route.pattern)
      if route.page.data["route"] == "/"
        # do extra checking to see if they asked for /index, /, or /home
        if %w(index home /).include? url
          return { :page => route.page } 
        else
          return {:page => nil}
        end
      else
        return { :page => route.page } 
      end
    end
  end
  return nil
end

#routesObject

todo: test



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/milksteak/cms.rb', line 25

def routes
  return @@routes if @@routes
  puts "LOADING ROUTES"
  load_pages if @@pages.empty?
  @@routes = { :primary => [], :dynamic => [] }
  @@pages.each do |page|
    r = Route.new(page)
    r.primary ? (@@routes[:primary] << r) : (@@routes[:dynamic] << r)
  end
  return @@routes
end