Class: Cloudsheet::Mapping

Inherits:
Object
  • Object
show all
Defined in:
lib/cloudsheet/mapping.rb

Constant Summary collapse

TO_S =
->(d) {d.to_s}
NOOP =
->(d) {d}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Mapping

Returns a new instance of Mapping.



6
7
8
9
10
# File 'lib/cloudsheet/mapping.rb', line 6

def initialize(name)
  @name = name
  @read = NOOP
  @write = NOOP
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/cloudsheet/mapping.rb', line 3

def name
  @name
end

#readObject (readonly)

Returns the value of attribute read.



3
4
5
# File 'lib/cloudsheet/mapping.rb', line 3

def read
  @read
end

Instance Method Details

#map(read, write = nil) ⇒ Object



12
13
14
15
16
# File 'lib/cloudsheet/mapping.rb', line 12

def map(read, write = nil)
  @read = read
  @write = write if write
  self
end

#type(klass) ⇒ Object



18
19
20
21
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
48
49
# File 'lib/cloudsheet/mapping.rb', line 18

def type(klass)
  klass = klass.to_s
  klass.downcase!
  case klass #Because case uses ===
  when ""
  when "noop"
  when "string"
    @read = ->(d) {String.new(d) if d}
    @write = TO_S
  when "date"
    @read = ->(d) {Date.parse(d) if not d.empty?}
    @write = TO_S
  when "float"
    @read = ->(d) {d.to_f if not d.empty?}
    @write = TO_S
  when "integer"
    @read = ->(d) {d.to_i if not d.empty?}
    @write = TO_S
  when "datetime"
    @read = ->(d) {DateTime.parse(d) if not d.empty?}
    @write = TO_S
  when "money"
    @read = ->(d) {d.gsub(',','').gsub('$','').to_f}
    @write = ->(d) {"$"+d.to_s}
  when "month"
    @read = ->(d) {Date.strptime(d, '%m/%Y') if not d.empty?}
    @write = ->(d) {d.strftime("%m/%Y")}
  else
    raise "No mapping for that type is built in"
  end
  self
end