Skip to content

Instantly share code, notes, and snippets.

@maxjacobson
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save maxjacobson/ab49a63511c77543b194 to your computer and use it in GitHub Desktop.

Select an option

Save maxjacobson/ab49a63511c77543b194 to your computer and use it in GitHub Desktop.
require 'yaml'
class MyOrm
attr_accessor :id, :destroyed
def save
!!self.class.write_new(self)
end
def destroy
!!self.class.remove(id)
end
def self.create(attributes = {})
record = self.new(attributes)
record.destroyed = false
record.id = next_id
record.save
record
end
def self.first
all.first
end
def self.last
all.last
end
def self.count
all.count
end
def self.remove(id)
if (object = find_by(id: id))
object.destroyed = true
objects = all
index = index_of(id)
objects[index] = object
write(objects)
else
false
end
end
def self.destroy_all
objects = all.map do |object|
object.destroyed = true
object
end
write(objects)
objects.count
end
def self.index_of(id)
all.index do |object|
object.id == id
end
end
def self.next_id
if (last_record = self.all_including_destroyed.last)
last_record.id + 1
else
1
end
end
def self.all
all_including_destroyed.reject(&:destroyed?)
end
def self.all_including_destroyed
YAML.load(raw_data) || []
end
def destroyed?
destroyed
end
def self.find_by(attributes)
all.detect do |object|
attributes.all? do |key, value|
object.send(key) == value
end
end
end
def self.write_new(object)
write(all_including_destroyed.push(object))
end
def self.write(objects)
File.open(filename, "w") do |f|
f.write YAML.dump(objects)
end
end
def self.raw_data
File.read(filename)
rescue Errno::ENOENT
""
end
def self.filename
"#{self.name.to_s.downcase}.yml"
end
def inspect
"#<#{self.class.name} " + instance_variables.map do |ivar|
"#{ivar}=#{instance_variable_get(ivar)}" unless [:@destroyed].include?(ivar)
end.compact.join(' ') + ">"
end
end
class Thundercat < MyOrm
attr_reader :name
def initialize(name: 'Snarf')
@name = name
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment