Skip to content

Instantly share code, notes, and snippets.

@jystewart
Created June 10, 2012 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jystewart/2906392 to your computer and use it in GitHub Desktop.
Save jystewart/2906392 to your computer and use it in GitHub Desktop.
Example decorator that could be used with GOV.UK API responses to extract tags by type
require 'active_support/inflector'
class TagTypeDecorator
def self.has_tag_types(*types)
types.each do |sym|
define_method sym do
taggable.tags.select { |t| t.tag_type == sym.to_s.singularize.capitalize }
end
end
end
has_tag_types :sections, :propositions, :audiences
attr_accessor :taggable
def initialize(taggable)
raise "Isn't taggable" unless taggable.respond_to?(:tags)
@taggable = taggable
end
def method_missing(method, *args)
args.empty? ? taggable.send(method) : taggable.send(method, *args)
end
end
require 'minitest/autorun'
class DecoratorTest < MiniTest::Unit::TestCase
class Tag
attr_accessor :tag_id, :tag_type
def initialize(attrs = {})
attrs.each { |k, v| __send__("#{k}=", v) }
end
end
class SampleArtefact
attr_accessor :stored_title
def title
@stored_title ||= "Bizarre"
@stored_title
end
def title=(value)
@stored_title = value
end
def tags
[
Tag.new(tag_id: 'driving/cars', tag_type: 'Section'),
Tag.new(tag_id: 'driving/bicycles', tag_type: 'Section'),
Tag.new(tag_id: 'policemen', tag_type: 'Audience'),
Tag.new(tag_id: 'business', tag_type: 'Proposition')
]
end
end
def setup
@artefact = SampleArtefact.new
@decorator = TagTypeDecorator.new(@artefact)
end
def test_it_gives_access_to_sections
assert_equal ['driving/cars', 'driving/bicycles'], @decorator.sections.collect(&:tag_id)
end
def test_it_gives_access_to_propositions
assert_equal ['business'], @decorator.propositions.collect(&:tag_id)
end
def test_it_gives_access_to_audiences
assert_equal ['policemen'], @decorator.audiences.collect(&:tag_id)
end
def test_it_should_retain_access_to_raw_tags
assert_equal 'driving/cars', @decorator.tags.first.tag_id
end
def test_it_should_retain_access_to_artefact_title
assert_equal 'Bizarre', @decorator.title
end
def test_it_should_retain_access_to_artefact_title_setter
@decorator.title= "Normal"
assert_equal 'Normal', @decorator.title
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment