Created
April 12, 2011 00:32
-
-
Save dhrrgn/914681 to your computer and use it in GitHub Desktop.
A nifty little Article model for Markdown file based articles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# You need to set the Article.path to where your files are located. | |
# I do this in my application_controller.rb | |
Article.path = File.join(Rails.root, 'articles') | |
class Article | |
attr_reader :title, :tags, :mtime, :slug, :filename | |
def self.path=(path) | |
@@path = path | |
end | |
def self.path | |
@@path | |
end | |
def self.all | |
@@articles = [] | |
Dir.glob(File.join(@@path, '**', '*.md')) do |file| | |
filename = file.gsub(@@path + '/', '') | |
path_parts = filename.split('/') | |
@@articles.push(new({ | |
:filename => filename, | |
:slug => filename.gsub('.md', ''), | |
:title => path_parts.pop.gsub('.md', '').to_human_title, | |
:tags => path_parts, | |
:mtime => File::mtime(file) | |
})) | |
end | |
@@articles | |
end | |
def self.find(slug) | |
all.detect { |article| article.slug == slug } || raise(ActiveRecord::RecordNotFound) | |
end | |
def <=>(x) | |
x.mtime <=> @mtime | |
end | |
def initialize(attributes) | |
@title = attributes[:title] | |
@slug = attributes[:slug] | |
@tags = attributes[:tags] | |
@mtime = attributes[:mtime] | |
@filename = attributes[:filename] | |
end | |
def content | |
file = File.join(@@path, @filename) | |
if File.exists?(file) | |
RDiscount.new(File.read(file)).to_html | |
else | |
nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment