require 'digest/sha1' require 'date' module Owl module Lib class Page DEFAULT_PAGE_LAYOUT = "default.haml" FRONT_MATTER_RE = /\A(---\s*\n.*?\n?)^(---\s*$\n?)/m attr_accessor :raw attr_accessor :haml attr_accessor :html attr_accessor :front_matter attr_accessor :path def initialize(path, current_scope=self, quiet=false) read(path) @path = path raise Sinatra::NotFound if (@raw.nil? and !quiet) @scope = current_scope @scope.instance_variable_set :@page, self parse_haml parse_front_matter render end def read(path) @raw ||= Cabi.read( Owl::Lib::Path.path(path) ) || Cabi.read( Owl::Lib::Path.page_path(path) ) end def parse_haml @haml ||= raw.gsub FRONT_MATTER_RE, '' end def parse_front_matter @front_matter ||= begin raise unless raw.index(FRONT_MATTER_RE) YAML.load(@raw) || Hash.new rescue Exception => e Hash.new end end def render @html = Haml::Engine.new( layout ).render( @scope, front_matter ) do Haml::Engine.new( @haml ).render( @scope, front_matter ) end end def content # This is the page without the content. @content ||= Haml::Engine.new( @haml ).render( @scope, front_matter ) end def setting(key) @front_matter[key] end def haml_opts opts = front_matter opts[:layout] = layout opts end def layout user_layout = setting('layout') Owl::Lib::Theme.instance.layout( user_layout ) end def type post? ? 'post' : 'page' end def page? !post? end def post? path.index("/post") == 0 end def cache? if @front_matter.has_key?('cache') setting('cache') else true end end def publish? setting('publish') end def age begin Date.parse(date).to_time.to_i rescue Exception => e 0 end end def sha1 Digest::SHA1.hexdigest @raw end def self.all_posts(current_scope=self, opts) files = Cabi.file( Owl::Lib::Path.all_posts_path ) posts = [] files.each do |path| path = '/' + path.gsub(Cabi::data_dir, '')[1..-1].split('/')[1..-2].join('/') post = Owl::Lib::Page.new( path, current_scope, true) posts << post if post.publish? or opts[:include_unpublished] end posts.sort! {|a,b| a.age <=> b.age } posts.reverse! posts end end end end