Module: Yamlet::Model

Defined in:
lib/yamlet.rb

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



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
# File 'lib/yamlet.rb', line 29

def self.included(klass)
  klass.define_singleton_method :resource_name, -> {
    name = klass.to_s.downcase
    name.gsub!("::", "_") if name.include? "::"

    return name
  }

  klass.define_singleton_method :store, -> { Yamlet::Repository.store }

  klass.store.transaction { klass.store[klass.resource_name] ||= [] }

  klass.define_singleton_method :all, -> {
    store.transaction { store[resource_name] }
  }

  klass.define_singleton_method :find, ->(id) {
    store.transaction { store[resource_name].select { |s| s["id"] == id }[0] }
  }

  klass.define_singleton_method :create, ->(attributes = {}) {
    # Auto increment ids
    ids = all.empty? ? [0] : all.map { |s| s["id"] }
    id  = ids[-1].zero? ? 1 : ids[-1].succ

    if attributes.empty?
      store.transaction { store[resource_name].push({ "id" => id }) }
    else
      store.transaction {
        store[resource_name].push(
          {}.tap do |hash|
            hash["id"] = id
            attributes.each_pair { |k, v| hash[k.to_s] = v }
          end
        )
      }
    end
  }

  klass.define_singleton_method :update, ->(id, attributes) {
    store.transaction {
      store[resource_name].select { |s| s["id"] == id }[0].tap do |record|
        attributes.each_pair { |k, v| record[k.to_s] = v } unless record.nil?
      end
    }
  }

  klass.define_singleton_method :destroy, ->(id) {
    store.transaction { store[resource_name].delete_if { |h| h["id"] == id } }
  }

  klass.define_singleton_method :destroy_all, -> {
    store.transaction { store[resource_name] = [] }
  }

end