Permalink
Browse files

Add YAML front matter parsing for response files

  • Loading branch information...
knuton committed Jan 8, 2012
1 parent 39a57d6 commit 0f73fa3fcce1229ca81839cf48048f3ffd3f3a76
Showing with 59 additions and 6 deletions.
  1. +4 −2 lib/second_mate/combined_logger.rb
  2. +32 −4 lib/second_mate/response.rb
  3. +23 −0 test/test_response.rb
@@ -1,7 +1,7 @@
module SecondMate
class CombinedLogger < Rack::CommonLogger
FORMAT = %{%s - %s [%s] "%s %s%s %s" %d %s %0.4f "%s"\n}
FORMAT = %{%s - %s [%s] "%s %s%s %s" %d %s %0.4f "%s" "%s"\n}
def log(env, status, header, began_at)
now = Time.now
@@ -19,8 +19,10 @@ def log(env, status, header, began_at)
status.to_s[0..3],
length,
now - began_at,
header['second_mate.response_file'] || 'NONE'
header.delete('second_mate.response_file') || 'NONE',
"YAML Frontmatter: #{header.delete('second_mate.yaml_frontmatter') || 'No'}"
]
end
end
@@ -4,13 +4,41 @@ module SecondMate
class Response < Rack::Response
attr_accessor :body, :params, :status, :header
def initialize(body=[], params={}, status=200, header={})
super render_template(body, params), status, header
@body = body
@params = params
@status = status
@header = header
process_yaml
render_template
super self.body, self.status, self.header
end
private
def process_yaml
if self.body =~ /^(---\s*\n.*?\n?)^(---\s*$\n?)/m
self.body = self.body[($1.size + $2.size)..-1]
begin
data = YAML.load($1)
# Use specified HTTP status
self.status = data['status'] if data['status']
# Fill header information
data['header'].each { |field, value| self.header[field] = value } if data['header'].kind_of? Hash
self.header['second_mate.yaml_frontmatter'] = 'Yes'
rescue => e
self.header['second_mate.yaml_frontmatter'] = 'Error'
end
end
end
def render_template(template, params)
erb = ERB.new template
erb.result binding
def render_template
erb = ERB.new @body
@body = erb.result binding
end
end
View
@@ -0,0 +1,23 @@
require 'test/unit'
require 'second_mate'
class TestResponse < Test::Unit::TestCase
def setup
@response = SecondMate::Response.new(
"---\nstatus: 201\nheader:\n Foo: Baz\n---\nBody",
{},
200,
{'Foo' => 'Bar'}
)
end
def test_yaml_frontmatter
response = @response.finish
assert_equal ['Body'], response.last.body
assert_equal 'Baz', response[1]['Foo']
end
end

0 comments on commit 0f73fa3

Please sign in to comment.