Class: Resto::Property::Time

Inherits:
Object
  • Object
show all
Includes:
Resto::Property
Defined in:
lib/resto/property/time.rb,
lib/resto/property/time.rb

Instance Method Summary collapse

Methods included from Resto::Property

#attribute_key, #attribute_key_as_string, #remote_key, #validate, #validate_inclusion, #validate_length, #validate_presence

Constructor Details

#initialize(name, options = {}) ⇒ Time

Returns a new instance of Time.



15
16
17
18
19
20
# File 'lib/resto/property/time.rb', line 15

def initialize(name, options={})
  @key = (name.to_s + "_time").to_sym
  @format = options[:format]
  @delimiter = @format.to_s.match(/(\W)/) { |m| m[0] }
  super
end

Instance Method Details

#cast(value, errors) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/resto/property/time.rb', line 22

def cast(value, errors)
  errors.store(@key, nil)

  formatted_value = value.to_s.strip
  if formatted_value.gsub(/([a-z|A-Z]{1,5}\Z)/, '') =~ /[^T\d\-:\+\/\s]/
    errors.store(@key, ":#{attribute_key} is not a valid time format.")
    formatted_value = ""
  end

  number_of_digits = formatted_value.gsub(/\D/, '').length
  if (1..9).include?(number_of_digits)
    errors.store(@key, ":#{attribute_key} is not a valid time format.")
    formatted_value = ""
  end

  begin
    if formatted_value.empty?
      nil
    else
      ::Time.parse(from_format(formatted_value))
    end
  rescue ArgumentError, TypeError, NoMethodError
    errors.store(@key, ":#{attribute_key} is not a valid time format.")
    nil
  end
end