Module: Model

Defined in:
lib/model.rb,
lib/model/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



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

def self.extended(base)
  class << base
    attr_accessor :instances, :callbacks
  end
  
  base.instance_eval do    
    attr_accessor :id
      
    define_method :save do
      if self.callback(:before_save)
        self.id = self.class.last.id + 1 rescue 1
        self.class.instances << self
        self.callback(:after_save)
        return true
      end
  
      return false
    end

    define_method :validate_uniqueness_of do |hash|
      field = hash[:value]
      scope_field = hash[:args] && hash[:args][:scope] ? hash[:args][:scope] : nil
              
      if scope_field
        result = self.class.all.select { |x| x.send(field) == self.send(field) && x.send(scope_field) == self.send(scope_field) }.count == 0
      else
        result = self.class.all.select { |x| x.send(field) == self.send(field) }.count == 0
      end
      
      result
    end
  
    define_method :callback do |c|
      ok = true
      self.class.callbacks[c].each do |key, value|
        if value
          ok &&= !(self.send(key, value) === false)
        else
          ok &&= !(self.send(key) === false)
        end
      end
      
      ok
    end
  end
  
  base.instances = []
  base.callbacks = {:before_create => {}, :after_create => {}, :before_save => {}, :after_save => {}}

  base.callbacks.each do |key, value|
    define_method key do |method|
      self.callbacks[key].merge!({method => nil})
    end
  end
end

Instance Method Details

#allObject



70
71
72
# File 'lib/model.rb', line 70

def all
  self.instances
end

#create(*args) ⇒ Object



83
84
85
86
87
88
89
90
# File 'lib/model.rb', line 83

def create(*args)
  s = self.new(*args)
  
  if s.callback(:before_create)
    s.save
    s.callback(:after_create)
  end
end

#destroy_allObject



74
75
76
# File 'lib/model.rb', line 74

def destroy_all
  self.instances = []
end

#find(hash) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/model.rb', line 60

def find(hash)
  results = self.instances

  hash.each do |key, value|
    results = results.select { |r| r.send(key) == value }
  end

  results
end

#lastObject



78
79
80
81
# File 'lib/model.rb', line 78

def last
  self.instances.sort! { |a,b| a.id <=> b.id}
  self.instances.last
end

#validate_uniqueness_of(field, hash = nil) ⇒ Object



92
93
94
# File 'lib/model.rb', line 92

def validate_uniqueness_of(field, hash = nil)
  self.callbacks[:before_create].merge!({:validate_uniqueness_of => {:value => field, :args => hash}})
end