Search code examples
ruby-on-railsruby-on-rails-4date-formatform-helpers

Show formatted date in f.text_field if present, else placeholder


The following code works to show the date only if it's present:

f.text_field :published_at, placeholder: "E.g. 12 Sep 2014", value: @post.try(:published_at)

But how would I format it?

This is how I'd format it if I knew that the date is present:

value: @post.published_at.strftime("%e %b %Y")

Solution

  • Wrap that around a helper function to change the format

    f.text_field :published_at, placeholder: "E.g. 12 Sep 2014", value: custom_format(@post.try(:published_at))
    

    some_helper.rb

    def custom_format(date)
      date ? date.strftime("%e %b %Y") : nil
    end