Skip to content

Commit

Permalink
Introduce Null Object.
Browse files Browse the repository at this point in the history
  • Loading branch information
josemotanet committed Jun 4, 2013
1 parent f07639d commit e0739b1
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 1 deletion.
37 changes: 37 additions & 0 deletions introduce-null-object/lib/after.rb
Original file line number Diff line number Diff line change
@@ -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)
)
]

31 changes: 31 additions & 0 deletions introduce-null-object/lib/before.rb
Original file line number Diff line number Diff line change
@@ -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)
)
]

12 changes: 11 additions & 1 deletion introduce-null-object/test/test.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit e0739b1

Please sign in to comment.