|
| 1 | +require 'date' |
| 2 | + |
| 3 | +module Pact |
| 4 | + module Generator |
| 5 | + # Date provides the time generator which will give the current date in the defined format |
| 6 | + class Date |
| 7 | + def can_generate?(hash) |
| 8 | + hash.key?('type') && hash['type'] == type |
| 9 | + end |
| 10 | + |
| 11 | + def call(hash, _params = nil, _example_value = nil) |
| 12 | + format = hash['format'] || default_format |
| 13 | + ::Time.now.strftime(convert_from_java_simple_date_format(format)) |
| 14 | + end |
| 15 | + |
| 16 | + def type |
| 17 | + 'Date' |
| 18 | + end |
| 19 | + |
| 20 | + def default_format |
| 21 | + 'yyyy-MM-dd' |
| 22 | + end |
| 23 | + |
| 24 | + # Format for the pact specficiation should be the Java DateTimeFormmater |
| 25 | + # This tries to convert to something Ruby can format. |
| 26 | + def convert_from_java_simple_date_format(format) |
| 27 | + # Year |
| 28 | + format.sub!(/(?<!%)y{4,}/, '%Y') |
| 29 | + format.sub!(/(?<!%)y{1,}/, '%y') |
| 30 | + |
| 31 | + # Month |
| 32 | + format.sub!(/(?<!%)M{4,}/, '%B') |
| 33 | + format.sub!(/(?<!%)M{3}/, '%b') |
| 34 | + format.sub!(/(?<!%)M{1,2}/, '%m') |
| 35 | + |
| 36 | + # Week |
| 37 | + format.sub!(/(?<!%)M{1,}/, '%W') |
| 38 | + |
| 39 | + # Day |
| 40 | + format.sub!(/(?<!%)D{1,}/, '%j') |
| 41 | + format.sub!(/(?<!%)d{1,}/, '%d') |
| 42 | + format.sub!(/(?<!%)E{4,}/, '%A') |
| 43 | + format.sub!(/(?<!%)D{1,}/, '%a') |
| 44 | + format.sub!(/(?<!%)u{1,}/, '%u') |
| 45 | + |
| 46 | + # Time |
| 47 | + format.sub!(/(?<!%)a{1,}/, '%p') |
| 48 | + format.sub!(/(?<!%)k{1,}/, '%H') |
| 49 | + format.sub!(/(?<!%)n{1,}/, '%M') |
| 50 | + format.sub!(/(?<!%)s{1,}/, '%S') |
| 51 | + format.sub!(/(?<!%)S{1,}/, '%L') |
| 52 | + |
| 53 | + # Timezone |
| 54 | + format.sub!(/(?<!%)z{1,}/, '%z') |
| 55 | + format.sub!(/(?<!%)Z{1,}/, '%z') |
| 56 | + format.sub!(/(?<!%)X{1,}/, '%Z') |
| 57 | + |
| 58 | + format |
| 59 | + end |
| 60 | + end |
| 61 | + end |
| 62 | +end |
0 commit comments