Skip to content

Instantly share code, notes, and snippets.

@TylerRick
Last active December 18, 2015 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TylerRick/5719558 to your computer and use it in GitHub Desktop.
Save TylerRick/5719558 to your computer and use it in GitHub Desktop.
date_field helper for HTML5 type="date" inputs! And a version of value_before_type_cast that returns a string in ISO-8601 format as the value for Dates, as specified by http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#date-state-(type=date)
# Extensions to gems/actionpack-3.2.13/lib/action_view/helpers/form_helper.rb
=begin
A version of InstanceTag.value_before_type_cast that returns a string in ISO-8601 format for Date columns.
The original behavior of value_before_type_cast was to return the Date object itself. But the default to_s on a Date returns a string like "June 5, 2013".
However, HTML5 date input fields expect their values to be in ISO-8601 format ("2013-06-05") and won't recognize the value if it is in some other format.
This makes it so you can simply do this:
f.date_field :some_date
and have it work as expected.
Otherwise you'd have to do something like this for every date_field:
f.date_field :some_date, value: f.object.some_date.to_s(:db)
=end
module ActionView
module Helpers
module FormHelper
InstanceTag.class_eval do
class << self
def value_before_type_cast_with_date_to_s(*args)
value_before_type_cast_without_date_to_s(*args).tap do |_|
return _.to_s(:db) if _.is_a? Date
end
end
alias_method_chain :value_before_type_cast, :date_to_s unless method_defined? :value_before_type_cast_without_date_to_s
end
end
# HTML5 date field. This should be part of Rails, like phone_field, email_field!
def date_field(object_name, method, options = {})
InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("date", options)
end
end
end
end
module ActionView
module Helpers
FormBuilder.class_eval do
%w(date_field).each do |selector|
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
def #{selector}(method, options = {}) # def text_field(method, options = {})
@template.send( # @template.send(
#{selector.inspect}, # "text_field",
@object_name, # @object_name,
method, # method,
objectify_options(options)) # objectify_options(options))
end # end
RUBY_EVAL
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment