Created
June 10, 2012 16:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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