Skip to content

Instantly share code, notes, and snippets.

@ArthurN
Created November 5, 2015 21:55
Show Gist options
  • Save ArthurN/e182bb609409e7878443 to your computer and use it in GitHub Desktop.
Save ArthurN/e182bb609409e7878443 to your computer and use it in GitHub Desktop.
module ChronicDateProperty #:nodoc:
extend ActiveSupport::Concern
module ClassMethods
# Define a Reform property which coerces its input via the Chronic parser.
def chronic_date_property(*args)
options = args.extract_options!
field = args.first
property(field, options)
# Setter (manual coercion)
define_method("#{field}=") do |val|
super(Chronic.parse(val).to_date)
end
end
end
end
class CompositeForm < Reform::Form
include Composition
include Reform::Form::Coercion
include ChronicDateProperty # our mixin
model :user
chronic_date_property :birthdate, on: :profile
validates :birthdate, presence: true
end
test do
form = CompositeForm.new(user: OpenStruct.new, profile: OpenStruct.new)
expect(form.validate({ birthdate: "12/03/1985" })).must_equal(true) # for the sake of completeness
form.save do |data|
expect(data[:profile]['birthdate']).must_be_kind_of(Date) # Now it fails! :(
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment