Created
November 5, 2015 21:55
-
-
Save ArthurN/e182bb609409e7878443 to your computer and use it in GitHub Desktop.
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
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 |
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
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 |
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
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