Kouhei Sutou
null+****@clear*****
Mon Feb 6 14:30:00 JST 2017
Kouhei Sutou 2017-02-06 14:30:00 +0900 (Mon, 06 Feb 2017) New Revision: 3145b325f8670922fce9a1c15f936314fa5ead16 https://github.com/ranguba/groonga-client-model/commit/3145b325f8670922fce9a1c15f936314fa5ead16 Message: Support Time key validation Modified files: lib/groonga_client_model/locale/en.yml lib/groonga_client_model/validations/type_validator.rb test/unit/test_record.rb Modified: lib/groonga_client_model/locale/en.yml (+2 -0) =================================================================== --- lib/groonga_client_model/locale/en.yml 2017-02-06 13:06:41 +0900 (aab86ca) +++ lib/groonga_client_model/locale/en.yml 2017-02-06 14:30:00 +0900 (81637a2) @@ -19,3 +19,5 @@ en: "must be between -(2 ** 31) and (2 ** 31) - 1: %{inspected_value}" invalid_int64: "must be between -(2 ** 63) and (2 ** 63) - 1: %{inspected_value}" + not_a_time: + "must be a time: %{inspected_value}" Modified: lib/groonga_client_model/validations/type_validator.rb (+26 -0) =================================================================== --- lib/groonga_client_model/validations/type_validator.rb 2017-02-06 13:06:41 +0900 (ecbefbd) +++ lib/groonga_client_model/validations/type_validator.rb 2017-02-06 14:30:00 +0900 (8b13a44) @@ -42,6 +42,8 @@ module GroongaClientModel validate_int(record, attribute, value, 64) when "Float" validate_float(record, attribute, value) + when "Time" + validate_time(record, attribute, value) end end @@ -112,6 +114,30 @@ module GroongaClientModel record.errors.add(attribute, :not_a_number) end end + + def validate_time(record, attribute, value) + if value.is_a?(String) + begin + value = Float(value) + rescue ArgumentError + begin + value = Time.strptime(value, "%Y-%m-%d %H:%M:%S.%N") + rescue ArgumentError + begin + value = Time.strptime(value, "%Y-%m-%d %H:%M:%S") + rescue ArgumentError + end + end + end + end + + case value + when Date, Time, Numeric + else + record.errors.add(attribute, :not_a_time, + options.merge(inspected_value: value.inspect)) + end + end end end end Modified: test/unit/test_record.rb (+14 -0) =================================================================== --- test/unit/test_record.rb 2017-02-06 13:06:41 +0900 (1f95b3b) +++ test/unit/test_record.rb 2017-02-06 14:30:00 +0900 (81e2e45) @@ -165,6 +165,14 @@ class TestRecord < Test::Unit::TestCase end end + class TimeKey < Key + class << self + def key_type + "Time" + end + end + end + sub_test_case("presence") do test "no key" do record = NoKey.new @@ -325,6 +333,12 @@ class TestRecord < Test::Unit::TestCase assert_invalid(FloatKey, "String", :not_a_number) end end + + sub_test_case("Time") do + test("invalid") do + assert_invalid(TimeKey, "String", :not_a_time) + end + end end end end -------------- next part -------------- HTML����������������������������...下载