Created
October 9, 2014 23:45
-
-
Save bethesque/e0ec87735da332a1d6a6 to your computer and use it in GitHub Desktop.
How to do a multipart updatable date with Reform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'date' | |
class Applicant | |
attr_accessor :date | |
end | |
applicant = Applicant.new | |
applicant.date = Date.new(2014, 10, 13) | |
require 'reform' | |
class Form < Reform::Form | |
property :date, virtual: true do | |
property :day | |
property :month | |
property :year | |
end | |
validate :validate_date | |
def sync | |
result = super | |
model.date = parse_date | |
result | |
end | |
def validate_date | |
unless valid_date? | |
errors.add(:date, "Invalid date") | |
end | |
end | |
def valid_date? | |
begin | |
parse_date | |
true | |
rescue ArgumentError => e | |
false | |
end | |
end | |
def parse_date | |
Date.new(date.year.to_i, date.month.to_i, date.day.to_i) | |
end | |
end | |
form = Form.new(applicant) | |
puts "Initial day #{form.date.day}" | |
form_data = {'date' => {'day' => '1','month' => '12','year' => '2015'}} | |
#form_data = {'date' => {'day' => '50','month' => '12','year' => '2015'}} | |
if form.validate(form_data) | |
puts "validation passed" | |
form.sync | |
else | |
puts "validation failed" | |
end | |
puts "Final day in form #{form.date.day}" | |
puts "Final day in model #{applicant.date.day}" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment