Module: PopulateMe::DocumentMixins::Typecasting

Included in:
PopulateMe::Document
Defined in:
lib/populate_me/document_mixins/typecasting.rb

Instance Method Summary collapse

Instance Method Details

#typecast(k, v) ⇒ Object

This module deals with typecasting the fields when they are received as strings, generally from a form or a csv file



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/populate_me/document_mixins/typecasting.rb', line 9

def typecast k, v
  unless self.class.fields.key?(k)
    return WebUtils.automatic_typecast(v) 
  end
  f = self.class.fields[k].dup
  meth = "typecast_#{f[:type]}".to_sym
  unless respond_to? meth
    return WebUtils.automatic_typecast(v, [f[:type],:nil])
  end
  __send__ meth, k, v
end

#typecast_attachment(k, v) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/populate_me/document_mixins/typecasting.rb', line 57

def typecast_attachment k, v
  attached = self.attachment k
  if WebUtils.blank? v
    attached.delete_all
    return nil
  elsif v.is_a?(Hash)&&v.key?(:tempfile)
    return attached.create v
  end
end

#typecast_date(k, v) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/populate_me/document_mixins/typecasting.rb', line 38

def typecast_date k, v
  if v[/\d\d(\/|-)\d\d(\/|-)\d\d\d\d/]
    Date.parse v
  elsif v[/\d\d\d\d(\/|-)\d\d(\/|-)\d\d/]
    Date.parse v
  else
    nil
  end
end

#typecast_datetime(k, v) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/populate_me/document_mixins/typecasting.rb', line 48

def typecast_datetime k, v
  if v[/\d\d(\/|-)\d\d(\/|-)\d\d\d\d \d\d?:\d\d?:\d\d?/]
    d,m,y,h,min,s = v.split(/[-:\s\/]/)
    Time.utc(y,m,d,h,min,s)
  else
    nil
  end
end

#typecast_integer(k, v) ⇒ Object



21
22
23
# File 'lib/populate_me/document_mixins/typecasting.rb', line 21

def typecast_integer k, v
  v.to_i
end

#typecast_price(k, v) ⇒ Object



25
26
27
28
# File 'lib/populate_me/document_mixins/typecasting.rb', line 25

def typecast_price k, v
  return nil if WebUtils.blank?(v)
  WebUtils.parse_price(v)
end

#typecast_select(k, v) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/populate_me/document_mixins/typecasting.rb', line 30

def typecast_select k, v
  if v.is_a?(Array)
    v.reject{|str| str=='nil' }
  else
    v
  end
end