recode page to parse dates

also return title and slug as separate pieces
and use haml as base extension
This commit is contained in:
Torsten Ruger 2017-06-12 17:49:49 +03:00
parent f627ce17cb
commit bffed0a7fb
2 changed files with 47 additions and 19 deletions

View File

@ -1,25 +1,39 @@
class Page
@@pages = nil
attr_reader :year , :month , :day , :title , :dir , :ext
attr_reader :year , :month , :day , :dir , :ext
def initialize(path)
@dir = File.dirname(path)
@base = File.basename(path)
@year , @month , @day , @title = @base.split("-")
raise "Invalid path #{path}" unless @title
@title , @ext = @title.split(".")
base , @ext = File.basename(path).split(".")
@words = base.split("-")
@year = parse_int(@words.shift , 2100)
@month = parse_int(@words.shift , 12)
@day = parse_int(@words.shift , 32)
raise "Invalid path #{path}" unless @words
end
def slug
@words.join("-")
end
def title
@words.join(" ")
end
def parse_int( value , max)
ret = value.to_i
raise "invalid value #{value} > #{max}" if ret > max or ret < 1
ret
end
def content
File.open(@dir + "/" + @base ).read
File.open("#{@dir}/#{year}-#{month}-#{day}-#{slug}.#{ext}" ).read
end
def self.pages
return @@pages if @@pages
@@pages ={}
Dir["#{self.blog_path}/*.*"].each do |file|
Dir["#{self.blog_path}/2*.haml"].each do |file|
page = Page.new(file)
@@pages[page.title] = page
@@pages[page.slug] = page
end
@@pages
end

View File

@ -20,28 +20,42 @@ RSpec.describe Page, type: :model do
expect(@page.title).to eq "title"
end
it "returns dates" do
expect(@page.year).to eq "1993"
expect(@page.month).to eq "2"
expect(@page.day).to eq "4"
expect(@page.year).to eq 1993
expect(@page.month).to eq 2
expect(@page.day).to eq 4
end
end
it "must start with a year" do
expect{Page.new("no-num-4-title")}.to raise_error RuntimeError
end
it "returns whole title" do
page = Page.new("1993-2-4-Multi-word-title")
expect(page.title).to eq "Multi word title"
end
it "returns slug" do
page = Page.new("1993-2-4-Multi-word-title")
expect(page.slug).to eq "Multi-word-title"
end
it "returns title without extension if given file name" do
page = Page.new("1993-2-4-title.rb")
expect(page.title).to eq "title"
end
it 'returns blog path' do
expect(Page.blog_path.ends_with?("spec/blog")).to be true
end
it "return a list of pages" do
expect(Page.pages.values.first.content.length).to be > 10
end
describe "page list" do
it "return a list of pages" do
pages = Page.pages
expect(pages.class).to eq Hash
expect(pages.length).to be > 0
end
it 'returns blog path' do
expect(Page.blog_path.ends_with?("spec/blog")).to be true
before :each do
@pages = Page.pages
@first = @pages.values.first
end
it "return a list of pages" do
expect(Page.pages.values.first.content.length).to be > 10
expect(@pages.class).to eq Hash
expect(@pages.length).to be > 0
end
end
end