-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3 from noriyotcp/extractor-class
Add Extractor class
- Loading branch information
Showing
4 changed files
with
56 additions
and
67 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,42 +1,17 @@ | ||
require 'thor' | ||
require 'commonmarker' | ||
require 'open-uri' | ||
|
||
module Headown | ||
class CLI < Thor | ||
desc 'extract <path>', 'extract headers from file path' | ||
|
||
def extract(file_path) | ||
raise Headown::NotMarkdownError.new(file_path: file_path) if File.extname(file_path) != '.md' | ||
|
||
file_data = URI.open(file_path, &:read) | ||
puts_headers(file_data) | ||
extractor = Headown::Extractor.new(file_path) | ||
puts extractor.headers | ||
rescue Headown::NotMarkdownError => e | ||
puts <<~MSG | ||
#{e.class}: | ||
#{e.message} | ||
MSG | ||
end | ||
|
||
private | ||
|
||
def header_nodes(data) | ||
doc = CommonMarker.render_doc(data) | ||
[].tap { |nodes| doc.walk { |node| nodes << node if node.type == :header } } | ||
end | ||
|
||
def build_header(node) | ||
text = '' | ||
node.each { |subnode| text = subnode.string_content if subnode.type == :text } | ||
'#' * node.header_level + " #{text}" | ||
end | ||
|
||
def extract_headers(file_data) | ||
header_nodes(file_data).map { |node| build_header(node) } | ||
end | ||
|
||
def puts_headers(file_data) | ||
puts extract_headers(file_data) | ||
end | ||
end | ||
end |
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
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