From e0739b1780bc614641b92069ccb3055e26fc3e0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Mota?= Date: Thu, 30 May 2013 14:36:28 +0100 Subject: [PATCH] Introduce Null Object. --- introduce-null-object/lib/after.rb | 37 +++++++++++++++++++++++++++++ introduce-null-object/lib/before.rb | 31 ++++++++++++++++++++++++ introduce-null-object/test/test.rb | 12 +++++++++- 3 files changed, 79 insertions(+), 1 deletion(-) diff --git a/introduce-null-object/lib/after.rb b/introduce-null-object/lib/after.rb index e69de29..160c4fb 100644 --- a/introduce-null-object/lib/after.rb +++ b/introduce-null-object/lib/after.rb @@ -0,0 +1,37 @@ +class Post + attr_reader :id, :title, :body, :created_at + def initialize id, title, body, created_at + @id = id + @title = title + @body = body + @created_at = created_at + @published = false + end + + def self.find_and_publish id + # database operation to retrieve data. We'll simulate it for now. + post = POSTS.find { |post| post.id == id } || NullPost.new + post.publish + end + + def publish + @published = true + end + +end + +class NullPost + def publish + # noop + end +end + +POSTS = [ + Post.new( + 1, + "Introduce Null Object Pattern", + "Post body should be here", + Time.new(2013,01,25) + ) +] + diff --git a/introduce-null-object/lib/before.rb b/introduce-null-object/lib/before.rb index e69de29..0688969 100644 --- a/introduce-null-object/lib/before.rb +++ b/introduce-null-object/lib/before.rb @@ -0,0 +1,31 @@ +class Post + attr_reader :id, :title, :body, :created_at + def initialize id, title, body, created_at + @id = id + @title = title + @body = body + @created_at = created_at + @published = false + end + + def self.find_and_publish id + # database operation to retrieve data. We'll simulate it for now. + post = POSTS.find { |post| post.id == id } + post.publish unless post.nil? + end + + def publish + @published = true + end + +end + +POSTS = [ + Post.new( + 1, + "Introduce Null Object Pattern", + "Post body should be here", + Time.new(2013,01,25) + ) +] + diff --git a/introduce-null-object/test/test.rb b/introduce-null-object/test/test.rb index a8f6974..58f77c4 100644 --- a/introduce-null-object/test/test.rb +++ b/introduce-null-object/test/test.rb @@ -1,5 +1,15 @@ -require 'minitest/spec' require 'minitest/autorun' +require 'minitest/spec' require 'before' if ENV["BEFORE"] require 'after' unless ENV["BEFORE"] + +describe Post do + it "is publishable" do + Post.find_and_publish(1).must_equal true + end + + it "does nothing if post is not found" do + Post.find_and_publish(0) + end +end