Module: Yarrow::Tools::ContentUtils
- Defined in:
- lib/yarrow/tools/content_utils.rb
Overview
Synchronous utility functions for working with filesystem content tasks.
Instance Method Summary collapse
- #extract_yfm(text, options = {}) ⇒ Object
-
#read_yfm(name) ⇒ Object
Pass in a source path and get back a parsed representation of the content if it is in a known text format.
- #write_yfm(name, text, meta) ⇒ Object
Instance Method Details
#extract_yfm(text, options = {}) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/yarrow/tools/content_utils.rb', line 40 def extract_yfm(text, ={}) pattern = /^(---\s*\n.*?\n?)^(---\s*$\n?)/m if text =~ pattern content = text.sub(pattern, "") begin if .key?(:symbolize_keys) = YAML.load($1, symbolize_names: true) else = YAML.load($1) end return [content, ] rescue Psych::SyntaxError => error if defined? ::Logger # todo: application wide logger #logger = ::Logger.new(STDOUT) #logger.error "#{error.message}" end return [content, nil] end end [text, nil] end |
#read_yfm(name) ⇒ Object
Pass in a source path and get back a parsed representation of the content if it is in a known text format. Mostly used as a fallback if a custom parser or processing chain is not configured for a content type.
Supported formats:
-
HTML template and document partials
-
Markdown documents
-
YAML documents
-
JSON (untested)
Works around meta and content source in multiple files or a single file with front matter.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/yarrow/tools/content_utils.rb', line 18 def read_yfm(name) path = if name.is_a?(Pathname) name else Pathname.new(name) end text = File.read(path, :encoding => 'utf-8') case path.extname when '.htm', '.md', '.txt', '.yfm' extract_yfm(text, symbolize_keys: true) # when '.md' # body, data = read_split_content(path.to_s, symbolize_keys: true) # [Kramdown::Document.new(body).to_html, data] when '.yml' [nil, YAML.load(File.read(path.to_s), symbolize_names: true)] when '.json' [nil, JSON.parse(File.read(path.to_s))] end end |
#write_yfm(name, text, meta) ⇒ Object
65 66 67 68 69 70 71 |
# File 'lib/yarrow/tools/content_utils.rb', line 65 def write_yfm(name, text, ) # Symbolized keys are better to deal with when manipulating data in # Ruby but are an interop nightmare when serialized so here we do a # round-trip through JSON encoding to ensure all keys are string # encoded before dumping them to the front matter format. File.write(name, [YAML.dump(.to_json), "---", text].join("\n")) end |