Allow either string or procs to be used in formatting DateTime objects#145
Allow either string or procs to be used in formatting DateTime objects#145
Conversation
| "birthday": 762739200 | ||
| } | ||
| ``` | ||
|
|
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
| format = field_format || Blueprinter.configuration.datetime_format | ||
| format.nil? ? value : value.strftime(format) | ||
|
|
||
| if format.nil? |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
| elsif format.is_a?(String) | ||
| value.strftime(format) | ||
| else | ||
| raise BlueprinterError, 'Cannot format DateTime object with invalid formatter' |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
| field :first_name, datetime_format: -> datetime { datetime.strftime("%s") } | ||
| end | ||
| end | ||
| it('raises a BlueprinterError') { expect{subject}.to raise_error(Blueprinter::BlueprinterError) } |
There was a problem hiding this comment.
Hmm the error here is based on us using a datetime formatter on an invalid field, correct? The error message we get reads 'Cannot format DateTime object with invalid formatter' The formatter in this test case is perfectly fine, no? I think we need an invalid field error or something.
There was a problem hiding this comment.
Nevermind I was confused. The message DOES NOT read 'Cannot format DateTime object with invalid formatter', rather it's 'Cannot format invalid DateTime object' which is perfectly valid.
| @@ -1,13 +1,15 @@ | |||
| module Blueprinter | |||
| class DateTimeFormatter | |||
| InvalidDateTimeFormatterError = Class.new(BlueprinterError) | |||
This aims to address #120
Previously, we had a global and field level option
datetime_formatwhich takes in a string representing the strptime format to format the Date/DateTime object. This PR enablesdatetime_formatto be either a String or a Proc. This enables more flexibility/control in how dates can be formatted. ( i.e. for those who want to have something like integer UNIX timestamps)This is something that can _technically already be achieved (only at the field-level) _ by passing a block directly to the field, however, now that datetime_format can be set globally, this allows us to set a global datetime_format Proc which will get invoked on any field that responds to
strptime, and matching field-level syntax in a more idiomatic way.Global Config Setting
If a global datetime_format is set (either as a string format or a Proc), this option will be
invoked and used to format all fields that respond to
strptime.Field-level Setting
Usage (String Option):
Output:
{ "name": "John Doe", "birthday": "03/04/1994" }Usage (Proc Option):
Output:
{ "name": "John Doe", "birthday": 762739200 }