Class: BlogTools::Commands::Generate

Inherits:
Thor
  • Object
show all
Defined in:
lib/blog-tools/commands/generate.rb

Overview

BlogTools::Commands::Generate handles post generation

It is a Thor-based CLI command set for generating blog posts It supports options like specifying a custom template, defining the author, setting tags, and defining the post content.

Examples:

Generate a basic post

blog-tools generate post "My post Title"

Generate a post with tags and author

blog-tools generate post "My post Title" --tags ruby blog --author username

See Also:

Instance Method Summary collapse

Instance Method Details

#post(title) ⇒ Nil

Generates a new blog post from a template

This command uses ERB templates to render a new post from a template You can customize the template, author, tags, and content, as well as where to save the file to.

Examples:

❯ blog-tools generate post example
[✓] Post generated at example.md

Parameters:

  • title (String)

    The title of the post

  • options (Hash)

    a customizable set of options

Returns:

  • (Nil)

See Also:

  • ERB
  • Date
  • String#Colorize


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
79
80
81
# File 'lib/blog-tools/commands/generate.rb', line 52

def post(title)
  config = File.exist?(Storage::CONFIG_FILE) ? YAML.load_file(Storage::CONFIG_FILE) : {}

  template_file = options[:template] || config['default_template'] || 'post.md'
  template_path = File.expand_path(File.join(Storage::TEMPLATES_DIR + template_file))

  return puts "[!] Template file not found: #{template_path}".colorize(:red) unless File.exist?(template_path)

  template = File.read(template_path)
  renderer = ERB.new(template)

  result = renderer.result_with_hash(
    title: title,
    date: Date.today.to_s,
    author: options[:author] || config['author'] || ENV['USER'] || 'unknown',
    tags: options[:tags] || config['tags'] || [],
    content: options[:content] ? File.read(File.expand_path(options[:content])) : ''
  )

  dir_path = "#{options[:output]}/"
  output_filename = if options[:output]
                      "#{dir_path}#{title}.md"
                    else
                      "#{title.downcase.strip.gsub(/\s+/,
                                                   '_')}.md"
                    end
  File.write(output_filename, result)

  puts "[✓] Post generated at #{output_filename}".colorize(:green)
end