Created
November 24, 2008 03:36
-
-
Save therealadam/28366 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# I wanted to build a really common example app but use Git as the backend | |
# instead of a database or the filesystem. And so here we are. | |
# | |
# (c) Copyright 2008 Adam Keys. MIT licensed or some-such. | |
# | |
require 'fileutils' | |
require 'rubygems' | |
gem 'mojombo-grit' | |
gem 'json' | |
gem 'money' | |
require 'grit' | |
require 'json' | |
require 'money' | |
# A product for sale | |
class Item | |
attr_reader :name, :price | |
# Create a new product. | |
# name - the name of the item | |
# price - the price of the item in cents | |
def initialize(name, price) | |
@name, @price = name, price | |
end | |
# Convert this item to JSON | |
def to_json | |
{:name => name, :price => price}.to_json | |
end | |
end | |
# A collection of items for a store | |
class Inventory | |
attr_accessor :items | |
def initialize(items=[]) | |
@items = items | |
end | |
end | |
# A collection of items some may call a store | |
class Store | |
module GitPersistence | |
# Save the store to a Git repository named for the store | |
def to_git_repo | |
create_store | |
create_repo | |
end | |
private | |
# Create the directory structure for the store data | |
def create_store | |
FileUtils.mkdir(name) | |
inventory.items.each_with_index do |item, index| | |
File.open(filename_for(index), 'w') do |f| | |
f.write(item.to_json) | |
end | |
end | |
end | |
# Create and populate the Git repository for saving the store | |
def create_repo | |
repo_path = "#{name}/.git" | |
Grit::GitRuby::Repository.init(repo_path) | |
repo = Grit::Repo.new(repo_path) | |
inventory.items.each_with_index do |item, index| | |
repo.add(filename_for(index)) | |
end | |
repo.commit_index('Create store') | |
end | |
# Generate the filename for a store item | |
def filename_for(index) | |
"#{name}/item-#{index}.json" | |
end | |
end | |
include GitPersistence | |
attr_reader :name, :inventory | |
# Create a new store | |
# name - the name of the store | |
def initialize(name) | |
@name = name | |
@inventory = Inventory.new | |
end | |
end | |
store = Store.new('TheStore') | |
store.inventory.items = [Item.new('shirt', Money.us_dollar(1999)), | |
Item.new('pants', Money.us_dollar(5999))] | |
store.to_git_repo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment