therealadam (owner)

Revisions

gist: 28366 Download_button fork
public
Public Clone URL: git://gist.github.com/28366.git
Embed All Files: show embed
gitcart.rb #
1
2
3
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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#
# 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