ValidatesTimeliness

repository·master·Indexed 23 days ago

https://github.com/adzap/validates_timeliness

A validation library for dates, times, and datetimes in Rails and ActiveModel applications. It provides comprehensive temporal restrictions (such as :before, :after, and :between), handles timezones and type casting, and includes shims for ActiveRecord and Mongoid. Features include a strict plugin parser, custom restriction shorthand symbols, and extensions for Rails date/time select helpers.

Tokens
3.9K
Snippets
6
Records
28
Agent score
81%

What's inside validates_timeliness

  1. Use Restriction Shorthand symbols

    master

    To avoid repetitive lambda definitions for common relative times (like today or now), you can use shorthand symbols. The plugin provides :today and :now by default.

    Example usage:

    validates_date :birth_date, on_or_before: :today

    You can define your own shorthand symbols in the setup block.

    # in the setup block
    config.restriction_shorthand_symbols.update(yesterday: lambda { 1.day.ago })
  2. Install ValidatesTimeliness

    master

    Add the gem to your Gemfile and run the installation commands to set up the configuration initializer and locale files.

    1. Add to Gemfile:
    gem 'validates_timeliness', '~> 8.0.0.beta1'
    1. Run bundler:
    $ bundle install
    1. Generate the configuration files:
    $ rails generate validates_timeliness:install
  3. Enable Extensions for Select Helpers

    master

    The plugin provides two extensions to improve the behavior of Rails date/time select helpers:

    1. Strict Parsing (enable_multiparameter_extension!): Prevents Rails from 'shifting' invalid dates (like June 31st) into valid ones. It treats them as invalid instead.
    2. Display Invalid Values (enable_date_time_select_extension!): Allows ActionView to redisplay invalid date/time values to the user in the form fields instead of showing a blank field.

    Both must be activated in the configuration setup block.

  4. Customize timeliness error messages

    master

    The validator allows you to override default error messages for specific restrictions or for invalid types.

    1. Type Errors: If a value cannot be parsed into the specified type, an error with the key invalid_[type] is added (e.g., invalid_datetime). You can customize this using [type]_message.
    2. Restriction Errors: If a restriction like before fails, you can customize the message using before_message.
  5. Configure ORM/ODM support and shims

    master

    While the plugin works with any ActiveModel compatible ORM, some ORMs convert invalid date/time assignments to nil, which prevents validation from catching the error. To fix this, you must activate a shim. The plugin includes shims for ActiveRecord and Mongoid.

    By default, the plugin extends ActiveRecord if it is loaded. To explicitly extend other ORMs, use the config.extend_orms setting in the setup block.

    ValidatesTimeliness.setup do |config|
      # Extend ORM/ODMs for full support (:active_record).
      config.extend_orms = [ :active_record ]
    end
  6. Configure Default Timezone and Dummy Date

    master

    The plugin requires a default timezone for parsing and type casting. If using ActiveRecord, this is set automatically. For other ORMs, you may need to set it manually.

    Additionally, since Ruby lacks a time-only type, time-only columns are evaluated using a dummy date (defaulting to 2000-01-01 in Rails). You can customize this dummy date.

    Config options:

    • config.default_timezone: Set the timezone (e.g., :utc).
    • config.dummy_date_for_time_type: Set a custom dummy date as an array of [year, month, day].
    # in the setup block
    config.default_timezone = :utc
    config.dummy_date_for_time_type = [2009, 1, 1]
  7. Enable the Plugin Parser

    master

    The plugin uses the timeliness gem as an extensible date and time parser. By default, the plugin parser is disabled. Enabling it allows strings assigned to attributes to be parsed using the timeliness gem logic, which is stricter than the standard Ruby parser.

    To enable it, set use_plugin_parser = true in the configuration setup block.

    # in the setup block
    config.use_plugin_parser = true
  8. Automatic Rails integration via Railtie

    master

    When used within a Rails application, validates_timeliness automatically integrates with ActiveRecord. It synchronizes ValidatesTimeliness.default_timezone with ActiveRecord.default_timezone and automatically loads the :active_record ORM support.

    Additionally, the Railtie performs the following automatic configurations:

    • Restriction Errors: Sets ValidatesTimeliness.ignore_restriction_errors to false in non-test environments (and true in test environments).
    • Date Format: If the underlying Timeliness gem is version 0.4+, it synchronizes Timeliness.configuration.ambiguous_date_format with the current Timeliness::Definitions.current_date_format.
  9. Handle multiparameter time inputs in ActiveModel

    master

    The ValidatesTimeliness::Extensions::AcceptsMultiparameterTime extension allows ActiveModel::Type classes (like Date, Time, and DateTime) to handle multiparameter assignments (hashes containing individual components like year, month, day, etc.) instead of just single scalar values.

    When a hash is passed to a field using these types, the extension attempts to reconstruct a valid time object using the keys provided in the hash. It validates that the components form a valid civil date before proceeding.

  10. Configure ValidatesTimeliness via the setup method

    master

    Use the ValidatesTimeliness.setup method to configure the plugin's behavior in a single block. This method yields the module itself, allowing you to set configuration options, and then automatically calls load_orms to initialize any specified ORM extensions.

    Common configuration options include:

    • extend_orms: An array of ORM symbols (e.g., [:active_record]) to enable full support.
    • ignore_restriction_errors: Boolean to determine if errors should be ignored when restriction options are evaluated.
    • restriction_shorthand_symbols: A hash of symbols mapping to procs for shorthand time/date restrictions.
    • use_plugin_parser: Boolean to enable the stricter, extensible plugin date/time parser.
    • default_timezone: The default timezone (e.g., :utc).
    • dummy_date_for_time_type: An array representing the dummy date part used for time-type values (e.g., [2000, 1, 1]).
  11. Use validation methods for dates, times, and datetimes

    master

    You can validate model attributes using specific validation methods or the generic validates method with a :timeliness key.

    Available methods:

    • validates_date: validates the value as a date.
    • validates_time: validates the value as time only (e.g., '12:20pm').
    • validates_datetime: validates the value as a full date and time.
    • validates: use the :timeliness key and set the type in the options hash.

    Temporal restrictions (options) can take a Date, Time, or DateTime object, a Proc/lambda, a Symbol (matching a method name), or a String.

    class Person < ActiveRecord::Base
      validates_date :date_of_birth, on_or_before: lambda { Date.current }
      # or
      validates :date_of_birth, timeliness: { on_or_before: lambda { Date.current }, type: :date }
    end