ruby-x.github.io/app/models/post.rb

59 lines
1.4 KiB
Ruby
Raw Normal View History

2018-04-10 18:11:33 +02:00
class Post
@@posts = nil
attr_reader :year , :month , :day , :dir , :ext
def initialize(path)
@dir = File.dirname(path)
base , @ext = File.basename(path).split(".")
2018-04-10 19:00:56 +02:00
raise "must be partial, start with _ not:#{base}" unless base[0] == "_"
2018-04-10 18:11:33 +02:00
@words = base.split("-")
@year = parse_int(@words.shift[1 .. -1] , 2100)
@month = parse_int(@words.shift , 12)
2018-04-10 19:00:56 +02:00
@day = parse_int(@words.shift , 32)
2018-04-10 18:11:33 +02:00
raise "Invalid path #{path}" unless @words
end
2018-04-10 19:00:56 +02:00
2018-04-10 18:11:33 +02:00
def slug
@words.join("-").downcase
end
def title
@words.join(" ")
end
def template_name
2018-04-22 12:35:13 +02:00
"#{year}-#{month.to_s.rjust(2, '0')}-#{day.to_s.rjust(2, '0')}-#{@words.join("-")}"
2018-04-10 18:11:33 +02:00
end
def date
2018-04-22 12:35:13 +02:00
Date.new(year,month,day)
2018-04-10 18:11:33 +02:00
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}/_#{template_name}.#{ext}" ).read
end
def summary
ret = content.split("%h2").first.gsub("%p", "<br/>").html_safe
ret[0 .. 400]
end
def self.posts
return @@posts if @@posts
2018-04-10 21:30:17 +02:00
posts ={}
2018-04-10 18:11:33 +02:00
Dir["#{self.blog_path}/_2*.haml"].reverse.each do |file|
post = Post.new(file)
2018-04-10 21:30:17 +02:00
posts[post.slug] = post
2018-04-10 18:11:33 +02:00
end
2018-04-10 21:30:17 +02:00
@@posts = posts.sort_by { |slug, post| post.sort_key }.reverse.to_h
end
def sort_key
year*10000 + month*1000 + day
2018-04-10 18:11:33 +02:00
end
def self.blog_path
Rails.configuration.blog_path
end
end