A code snippet to start from
mkdir -p ~/Code/
pushd ~/Code/
git clone https://gist.github.com/5809220.git pplpkr
pushd ./pplpkr/
| # This adds JSON.parse and Array#to_json | |
| # json is just a way to format arrays, maps, strings, numbers, boolean, and nil for saving in a file | |
| require("json") | |
| # In order for something to be `require`-able, it must be a class or module | |
| class Model | |
| # this method simply saves a ruby object to a file (in json format) | |
| def self.save(filename, stuff) | |
| File.open(filename, "w") { |f| | |
| # objects only have a to_json method when json is required | |
| f.write(stuff.to_json) | |
| } | |
| end | |
| # this method simply loads a ruby object from a file (in json format) | |
| def self.load(filename) | |
| begin | |
| File.open(filename, "r") { |f| | |
| data = f.read() | |
| # JSON only exists when json is required | |
| return JSON.parse(data) | |
| } | |
| rescue | |
| return nil | |
| end | |
| end | |
| end |
| ["Theo", "Megan", "Bryan", "Travis"] |
| #!/usr/bin/env ruby | |
| require("./model") | |
| names = Model.load("names.json") | |
| p(names) | |
| Model.save("names.json", names) |