Skip to content

Instantly share code, notes, and snippets.

@hannahwhy
Created December 12, 2012 20:11
Show Gist options
  • Save hannahwhy/4271126 to your computer and use it in GitHub Desktop.
Save hannahwhy/4271126 to your computer and use it in GitHub Desktop.
diff --git a/app/models/response.rb b/app/models/response.rb
index c657a5f..531577f 100644
--- a/app/models/response.rb
+++ b/app/models/response.rb
@@ -29,8 +29,10 @@ class Response < ActiveRecord::Base
include Surveyor::Models::ResponseMethods
##
- # Used by {#value=} to recognize datetimes.
+ # Used by {#value=} to recognize datetimes, dates, and times.
ISO8601_HHMM_FORMAT = /\A\s*\d{4}-\d{2}-\d{2}T\d{2}:\d{2}([+-]\d{4}|Z)\s*\Z/
+ DATE_FORMAT = /\A\s*\d{4}-\d{2}-\d{2}\s*\Z/
+ TIME_FORMAT = /\A\s*\d{2}:\d{2}\s*\Z/
def self.default_scope; end
@@ -61,8 +63,18 @@ class Response < ActiveRecord::Base
def value=(val)
case val
when String
+ # This is pretty crazy.
+ #
+ # See
+ # https://github.com/NUBIC/surveyor/blob/0a4424ce6b732d111954354ec9c1c7e21d6ebc9b/lib/surveyor/models/response_methods.rb#L92-L103
+ # for Surveyor expectations on presenting dates, times, and datetimes as
+ # JSON.
if val =~ ISO8601_HHMM_FORMAT
self.datetime_value = Time.parse(val)
+ elsif val =~ DATE_FORMAT
+ self.date_value = val
+ elsif val =~ TIME_FORMAT
+ self.time_value = val
end
self.string_value = val
diff --git a/spec/models/response_spec.rb b/spec/models/response_spec.rb
index 2cbc540..8f78ed0 100644
--- a/spec/models/response_spec.rb
+++ b/spec/models/response_spec.rb
@@ -106,6 +106,26 @@ describe Response do
end
end
+ describe 'given a date in the form YYYY-MM-DD' do
+ let(:val) { '2012-12-04' }
+
+ it 'roundtrips to JSON' do
+ subject.answer = Factory(:answer, :response_class => 'date')
+
+ subject.json_value.should == '2012-12-04'
+ end
+ end
+
+ describe 'given a time in the form HH:MM' do
+ let(:val) { '12:00' }
+
+ it 'roundtrips to JSON' do
+ subject.answer = Factory(:answer, :response_class => 'time')
+
+ subject.json_value.should == '12:00'
+ end
+ end
+
it 'sets #string_value' do
subject.string_value.should == val
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment