Module: PDF::Toolkit::Coercions

Included in:
PDF::Toolkit
Defined in:
lib/pdf/toolkit/coercions.rb

Instance Method Summary collapse

Instance Method Details

#cast_field(field) ⇒ Object

From PDF to Ruby



6
7
8
9
10
11
12
13
14
15
# File 'lib/pdf/toolkit/coercions.rb', line 6

def cast_field(field)
  case field
  when /^D:(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)([-+].*)?/
    parse_time(field)
  when /^\d+$/
    field.to_i
  else
    field
  end
end

#format_field(field) ⇒ Object

From Ruby to PDF



37
38
39
40
41
42
43
# File 'lib/pdf/toolkit/coercions.rb', line 37

def format_field(field)
  if field.kind_of?(Time)
    format_time(field)
  else
    field
  end
end

#format_time(time) ⇒ Object



45
46
47
48
49
# File 'lib/pdf/toolkit/coercions.rb', line 45

def format_time(time)
  string = ("D:%04d"+"%02d"*5) % time.to_a[0..5].reverse
  string += (time.utc_offset < 0 ? "-" : "+")
  string += "%02d'%02d'" % [time.utc_offset.abs/3600,(time.utc_offset.abs/60)%60]
end

#parse_time(string) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/pdf/toolkit/coercions.rb', line 17

def parse_time(string)
  if string =~ /^D:(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)([-+].*)?/
    date = $~[1..6].map {|n|n.to_i}
    tz = $7
    time = Time.utc(*date)
    tz_match = tz.match(/^([+-])(\d{1,2})(?:'(\d\d)')?$/) if tz
    if tz_match
      direction, hours, minutes = tz_match[1..3]
      offset = (hours.to_i*60 + minutes.to_i)*60
      # Go the *opposite* direction
      time += (offset == "+" ? -offset : offset)
    end
    time
  else
    raise ArgumentError, "Unable to coerce `#{string}` to a Date"
  end
end