-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnew_post.rb
executable file
·79 lines (65 loc) · 2.01 KB
/
new_post.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
71
72
73
74
75
76
77
78
#!/usr/bin/env ruby
require 'optparse'
require 'ostruct'
require 'yaml'
EDITOR = "vim --cmd ':set spell spelllang=en_us'"
class ParseOptions
def self.parse(args)
options = OpenStruct.new
options.title = "Untitled"
time = Time.new
options.time = time.strftime("%Y-%m-%d %H:%M:%S")
options.stamp = time.strftime("%H%M%S")
options.date = time.strftime("%Y-%m-%d")
opts = OptionParser.new do |opts|
opts.banner = "Usage: new_post.rb [options]"
opts.separator ""
opts.separator "Options:"
opts.on("-t", "--title TITLE", "Supply Post Title") do |t|
options.title = t
end
opts.on("-c", "--content <file>", "Supply Post Content") do |c|
options.content = c
end
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
opts.parse!(args)
options
end
end
class Post
def self.build(options,filename)
header = build_header(options)
if options.content && File.exist?(options.content)
content = File.read(options.content)
file = File.new("_posts/#{filename}", "w")
file.write(header+content)
file.close
else
build_content(header,filename)
end
end
def self.build_header(options)
"---\nlayout: post\ntitle: #{options.title}\ndate: #{options.time}\ncategories:\n---\n\n"
end
def self.build_content(header,filename)
tmpfile = "/tmp/tmp-#{filename}"
system("echo '#{header}' > #{tmpfile}")
system("#{EDITOR} #{tmpfile}")
if filename =~ /Untitled/
getYaml = YAML.load_file("#{tmpfile}")
new_filename = filename.gsub("Untitled","#{getYaml["title"].gsub(' ','-')}")
system("cp #{tmpfile} _posts/#{new_filename} && rm #{tmpfile}")
else
system("cp #{tmpfile} _posts/#{filename} && rm #{tmpfile}")
end
end
end
options = ParseOptions.parse(ARGV)
filename = "#{options.date}-#{options.title.gsub(' ','-')}-#{options.stamp}.markdown"
post = Post.build(options,filename)
system("./deploy.rb")
puts "All done!"