Quick Start¶
Parse a String¶
require 'pm'
parsed = PM.parse("---\ntitle: Hello\n---\nContent here")
parsed.metadata.title #=> "Hello"
parsed.content #=> "Content here"
The content is everything after the closing --- line. Interior blank lines and
a trailing newline in the source are preserved as written.
Parse a File¶
Given greeting.md:
# Any of these forms work:
parsed = PM.parse('greeting.md') # explicit .md extension
parsed = PM.parse(:greeting) # Symbol: .md appended
parsed = PM.parse('greeting') # single word: .md appended
parsed.metadata.title #=> "Greeting"
parsed.parameters #=> {"name" => nil}
# Render with parameters
puts parsed.to_s('name' => 'Alice')
#=> "Hello, Alice! Welcome."
When parsing a file, PM also adds directory, name, created_at, and modified_at to the metadata.
Parse a String Directly¶
PM.parse treats single words as prompt IDs and looks them up as files. To always parse a string as content, use PM.parse_string:
PM.parse('hello') #=> looks for hello.md in prompts_dir
PM.parse_string('hello') #=> parses "hello" as string content
parsed = PM.parse_string("---\ntitle: Inline\n---\nSome content")
parsed.metadata.title #=> "Inline"
parsed.content #=> "Some content"
Parameters¶
Parameters declared in the YAML front matter define template variables:
nullvalue -- parameter is required;to_sraisesPM::MissingParameterErrorif missing- Any other value -- used as the default; can be overridden in
to_s
parsed = PM.parse("---\nparameters:\n lang: ruby\n code: null\n---\n<%= lang %>: <%= code %>")
# Use defaults where available, supply required params
parsed.to_s('code' => 'puts "hi"') #=> "ruby: puts \"hi\""
# Override defaults
parsed.to_s('code' => 'print("hi")', 'lang' => 'python')
parsed.to_s
#=> PM::MissingParameterError: Missing required parameters: code
Shell Expansion¶
Environment variables and commands are expanded at parse time:
Composing Prompts¶
---
parameters:
code: null
---
<%= include 'common/header.md' %>
Review this code:
<%= code %>
<%= insert 'app/models/user.rb' %>
include parses and renders another prompt file with the same parameters.
insert (alias read) copies any file in verbatim.
Next Steps¶
- Configuration -- Set a prompts directory and global defaults
- Parsing Guide -- File vs string parsing in depth
- Parameters Guide -- Required and default parameters
- Security Guide -- What a prompt file is allowed to do