summaryrefslogtreecommitdiff
path: root/lib/humble/column.rb
blob: 66ab233240945bbfd559cd5860fbd01c4f29a5dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
module Humble
  class Column
    attr_reader :column_name

    def initialize(name)
      @column_name = name
    end

    def prepare(entity)
      return {} if primary_key? && has_default_value?(entity)
      { column_name.to_sym => entity.public_send(column_name.to_sym) }
    end

    def matches?(column_name)
      @column_name == column_name
    end

    def apply(row, entity, session)
      value = row[column_name]
      entity.public_send("#{@column_name}=", value)
    end

    def primary_key?
      false
    end
  end

  class PrimaryKeyColumn < Column
    attr_reader :default

    def initialize(name, default)
      super(name)
      @default = default
    end

    def destroy(connection, entity)
      connection.where(column_name.to_sym => entity.id).delete
    end

    def primary_key?
      true
    end

    def has_default_value?(entity)
      entity.id == nil || @default == entity.id
    end
  end

  class BelongsTo < Column
    def initialize(name, type)
      super(name)
      @type = type
    end

    def apply(row, entity, session)
      value = row[column_name]
      entity.public_send("#{attribute_name}=", session.find(@type, value))
    end

    def prepare(entity)
      { column_name.to_sym => '' }
    end

    private

    def attribute_name
      column_name.to_s.gsub(/_id/, '')
    end
  end

  class HasMany < Column
    def initialize(attribute, type)
      super(attribute)
      @attribute, @type = attribute, type
    end

    def apply(row, entity, session)
      items = session.find_all(@type)
      entity.public_send("#{@attribute}=", items)
    end

    def prepare(entity)
      { }
    end
  end
end