« Back to Index

Ruby Decorator Design Pattern for BBC: with a little imagination you can see how we could store data in S3 instead of “printing” it to the screen AND also how we could have some models extend based on a whitelist (as some components you’ll want to extend ALL formatters, and other components you’ll only want to extend from one or two formatters)

View original Gist on GitHub

Ruby Decorator Design Pattern for BBC.rb

require "json"

module HtmlFormatter
  def render
    p "<p>HTML content</p>"
    super
  end
end

module JsonFormatter
  def render
    p JSON.generate :foo => :bar
    super
  end
end

module EnvelopeFormatter
  def render
p <<EOF
{
  "head": [
    "<link ... />",
    "<link ... />",
    "<meta ... />,",
    "<script ... />"
  ],
  "bodyInline": "<p>Some HTML here</p>",
  "bodyLast": [
    "<script>alert('script A');</script>",
    "<script>alert('script B');</script>"
  ]
}
EOF
    super
  end
end

class Model
  def render
    p "Plain Text"
  end
end

component = Model.new

component.extend(HtmlFormatter)
component.extend(JsonFormatter)
component.extend(EnvelopeFormatter)

component.render

=begin
"{\n  \"head\": [\n    \"<link ... />\",\n    \"<link ... />\",\n    \"<meta ... />,\",\n    \"<script ... />\"\n  ],\n  \"bodyInline\": \"<p>Some HTML here</p>\",\n  \"bodyLast\": [\n    \"<script>alert('script A');</script>\",\n    \"<script>alert('script B');</script>\"\n  ]\n}\n"
"{\"foo\":\"bar\"}"

"<p>HTML content</p>"

"Plain Text"
=end