Class: YAML::Record

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

Constant Summary collapse

@@before_save_methods =
Array.new
@@after_save_methods =
Array.new

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRecord

Returns a new instance of Record.



50
51
52
53
# File 'lib/yaml_adapter.rb', line 50

def initialize
  @created_at = Time.now.to_f
  @modified_at = @created_at
end

Class Method Details

.after_save(*methods) ⇒ Object



114
115
116
# File 'lib/yaml_adapter.rb', line 114

def self.after_save *methods
  @@after_save_methods = methods if methods.all? { |el| el.class == Symbol }
end

.allObject



102
103
104
# File 'lib/yaml_adapter.rb', line 102

def self.all
  YAML::Adapter.entities.find_all { |entity| entity.class == self }
end

.before_save(*methods) ⇒ Object



110
111
112
# File 'lib/yaml_adapter.rb', line 110

def self.before_save *methods
  @@before_save_methods = methods if methods.all? { |el| el.class == Symbol }
end

.create(options = {}) ⇒ Object



88
89
90
91
92
93
94
# File 'lib/yaml_adapter.rb', line 88

def self.create options = {}
  object = self.new
  options.keys.each do |key|
    object.instance_variable_set("@#{key.to_s}", options[key])
  end
  object
end

.create!(options = {}) ⇒ Object



96
97
98
99
100
# File 'lib/yaml_adapter.rb', line 96

def self.create! options = {}
  object = self.create(options)
  object.save!
  object
end

.find(id) ⇒ Object



106
107
108
# File 'lib/yaml_adapter.rb', line 106

def self.find id
  YAML::Adapter.entities.find { |entity| entity.id == id }
end

Instance Method Details

#created_atObject



80
81
82
# File 'lib/yaml_adapter.rb', line 80

def created_at
  Time.at(@created_at)
end

#destroy!Object



67
68
69
70
# File 'lib/yaml_adapter.rb', line 67

def destroy!
  FileUtils.rm(self.file_name)
  YAML::Adapter.entities.delete(self)
end

#file_nameObject



76
77
78
# File 'lib/yaml_adapter.rb', line 76

def file_name
  [self.id, '.yml'].join
end

#idObject



72
73
74
# File 'lib/yaml_adapter.rb', line 72

def id
  Digest::SHA1.hexdigest("#{self.class.name}_#{@created_at}")
end

#modified_atObject



84
85
86
# File 'lib/yaml_adapter.rb', line 84

def modified_at
  Time.at(@modified_at)
end

#save!Object



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/yaml_adapter.rb', line 55

def save!
  @@before_save_methods.each { |m| self.send(m) }
  @modified_at = Time.now.to_f
  content = self.to_yaml
  file = File.new(self.file_name, 'w')
  file.write(content)
  file.close
  @@after_save_methods.each { |m| self.send(m) }
  YAML::Adapter.reload
  self
end