Permalink
Browse files

Replace Subclasses with Strategies: Step One

* Extract one method to a strategy for each subclass
  • Loading branch information...
jferris committed Jan 31, 2013
1 parent 4939d3e commit 7747366a12b3f6f21d0008063c5655faba8e4890
@@ -12,7 +12,7 @@ def options_for_form
end

def score(text)
options.score(text)
submittable.score(text)
end

def breakdown
@@ -24,4 +24,8 @@ def breakdown
end
percents.join(', ')
end

def submittable
MultipleChoiceSubmittable.new(self)
end
end
@@ -0,0 +1,15 @@
class MultipleChoiceSubmittable
def initialize(question)
@question = question
end

def score(text)
options.score(text)
end

private

def options
@question.options
end
end
@@ -1,10 +1,14 @@
class OpenQuestion < Question
def score(text)
0
submittable.score(text)
end

def breakdown
text_from_ordered_answers = answers.order(:created_at).pluck(:text)
text_from_ordered_answers.join(', ')
end

def submittable
OpenSubmittable.new
end
end
@@ -0,0 +1,5 @@
class OpenSubmittable
def score(text)
0
end
end
@@ -3,7 +3,7 @@ class ScaleQuestion < Question
validates :minimum, presence: true

def score(text)
text.to_i
submittable.score(text)
end

def steps
@@ -13,4 +13,8 @@ def steps
def breakdown
sprintf('Average: %.02f', answers.average('text'))
end

def submittable
ScaleSubmittable.new
end
end
@@ -0,0 +1,5 @@
class ScaleSubmittable
def score(text)
text.to_i
end
end
@@ -0,0 +1,12 @@
describe MultipleChoiceSubmittable, '#score' do
it 'returns the score for the option with the given text' do
question = build_stubbed(:multiple_choice_question)
submittable = MultipleChoiceSubmittable.new(question)
question.options.target.stubs(score: 2)

result = submittable.score('two')

question.options.target.should have_received(:score).with('two')
result.should eq 2
end
end
@@ -0,0 +1,9 @@
describe OpenSubmittable, '#score' do
it 'returns zero' do
submittable = OpenSubmittable.new

result = submittable.score('anything')

result.should eq 0
end
end
@@ -0,0 +1,9 @@
describe ScaleSubmittable, '#score' do
it 'returns the integer value of the text' do
submittable = ScaleSubmittable.new

result = submittable.score('5')

result.should eq 5
end
end

0 comments on commit 7747366

Please sign in to comment.