Search code examples
ruby-on-railsrubydatedate-formattingruby-2.4

Change Date default to_s format in the scope of library


I want all of the dates in the scope of the library to have a common format ("%d.%m.%Y") instead of the default ("%Y-%d-%m"). For now I have come up with 3 different approaches (and I don't like any of them) to accomplish what I want. All of them are represented below in order from most to less painful:

  1. explicitly define all the attributes with dates and convert them in the necessary format in the exporter;
  2. redefine to_s method for each Date instance with the necessary format;
  3. define a custom descendant of a Date class with a custom to_s method.

Additional information:

  • The initial object can have up to 3 nestings with attributes of Date type on each of them;
  • The names of the attributes of Date type can vary;
  • I am using Virtus gem.

The question is as follows:

Is there a better way to handle the issue I am struggling with (and if not, what is the most elegant way to go between the ones that are already represented above)?


Solution

  • Create another module with a refinement to Date::to_s

    module MyDate
      refine Date do
        def to_s
          # here goes your implementation of to_s
        end
      end
    end
    

    And then:

     class NeedsCustomDateFormat
      using MyDate
      # All Date instances will have the custom to_s
     end