Permalink
Browse files

Moneta::YAML. Just another option really.

Signed-off-by: Yehuda Katz <wycats@gmail.com>
  • Loading branch information...
1 parent 887f8c0 commit abd3afc4ab56470b3333848bca1dd212785f76db @dylanegan dylanegan committed with Aug 11, 2009
Showing with 113 additions and 0 deletions.
  1. +92 −0 lib/moneta/yaml.rb
  2. +21 −0 spec/moneta_yaml_spec.rb
View
@@ -0,0 +1,92 @@
+require "yaml"
+require "fileutils"
+
+module Moneta
+ class YAML
+ class Expiration
+ def initialize(file)
+ @file = file
+ end
+
+ def [](key)
+ yaml[key]['expires'] if yaml.has_key?(key)
+ end
+
+ def []=(key, value)
+ hash = yaml
+ if hash.has_key?(key)
+ hash[key]['expires'] = value
+ save(hash)
+ end
+ end
+
+ def delete(key)
+ hash = yaml
+ if hash.has_key?(key)
+ hash[key].delete("expires")
+ save(hash)
+ end
+ end
+
+ private
+ def yaml
+ ::YAML.load_file(@file)
+ end
+
+ def save(hash)
+ ::File.open(@file, "w") { |file| file << hash.to_yaml }
+ end
+ end
+
+ def initialize(options = {})
+ @file = File.expand_path(options[:path])
+ unless ::File.exists?(@file)
+ File.open(@file, "w") { |file| file << {}.to_yaml }
+ end
+
+ @expiration = Expiration.new(@file)
+ end
+
+ module Implementation
+ def key?(key)
+ yaml.has_key?(key)
+ end
+
+ alias has_key? key?
+
+ def [](key)
+ yaml[key]['value'] if yaml.has_key?(key)
+ end
+
+ def []=(key, value)
+ hash = yaml
+ (hash[key] ||= {})['value'] = value
+ save(hash)
+ end
+
+ def delete(key)
+ hash = yaml
+ value = self[key]
+ hash.delete(key)
+ save(hash)
+ value
+ end
+
+ def clear
+ save
+ end
+
+ private
+ def yaml
+ ::YAML.load_file(@file)
+ end
+
+ def save(hash = {})
+ ::File.open(@file, "w") { |file| file << hash.to_yaml }
+ end
+ end
+ include Implementation
+ include Defaults
+ include Expires
+ end
+end
View
@@ -0,0 +1,21 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+begin
+ require "moneta/yaml"
+
+ describe "Moneta::YAML" do
+ before(:each) do
+ @cache = Moneta::YAML.new(:path => File.join(File.dirname(__FILE__), "yaml_cache"))
+ @cache.clear
+ end
+
+ after(:all) do
+ FileUtils.rm_rf(File.join(File.dirname(__FILE__), "yaml_cache"))
+ end
+
+ if ENV['MONETA_TEST'].nil? || ENV['MONETA_TEST'] == 'yaml'
+ it_should_behave_like "a read/write Moneta cache"
+ end
+ end
+rescue SystemExit
+end

0 comments on commit abd3afc

Please sign in to comment.