From 3a00353f83998faaa7db88676d2f052c44ecf452 Mon Sep 17 00:00:00 2001 From: Jim Myhrberg Date: Thu, 10 Mar 2011 00:24:35 +0000 Subject: [PATCH] created Options module to help organize the multiple options passed from one object to another --- lib/redistat.rb | 3 ++- lib/redistat/options.rb | 43 +++++++++++++++++++++++++++++++++++++++++ spec/options_spec.rb | 36 ++++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 lib/redistat/options.rb create mode 100644 spec/options_spec.rb diff --git a/lib/redistat.rb b/lib/redistat.rb index d3f1dc5..6aa628c 100644 --- a/lib/redistat.rb +++ b/lib/redistat.rb @@ -9,9 +9,10 @@ require 'time_ext' require 'json' require 'digest/sha1' -require 'redistat/collection' +require 'redistat/options' require 'redistat/connection' require 'redistat/database' +require 'redistat/collection' require 'redistat/date' require 'redistat/date_helper' require 'redistat/event' diff --git a/lib/redistat/options.rb b/lib/redistat/options.rb new file mode 100644 index 0000000..252b508 --- /dev/null +++ b/lib/redistat/options.rb @@ -0,0 +1,43 @@ +module Redistat + module Options + + def self.included(base) + base.extend(ClassMethods) + end + + class InvalidDefaultOptions < ArgumentError; end + + module ClassMethods + def option_accessor(*opts) + opts.each do |option| + define_method(option) do |*args| + if !args.first.nil? + options[option.to_sym] = args.first + else + options[option.to_sym] || nil + end + end + end + end + end + + def parse_options(opts) + opts ||= {} + @raw_options = opts + @options = default_options.merge(opts.reject { |k,v| v.nil? }) + end + + def default_options + {} + end + + def options + @options ||= {} + end + + def raw_options + @raw_options ||= {} + end + + end +end \ No newline at end of file diff --git a/spec/options_spec.rb b/spec/options_spec.rb new file mode 100644 index 0000000..b00cd7d --- /dev/null +++ b/spec/options_spec.rb @@ -0,0 +1,36 @@ +require "spec_helper" + +describe Redistat::Options do + + before(:each) do + @helper = OptionsHelper.new + @helper.parse_options(:wtf => 'dude', :foo => 'booze') + end + + it "should #parse_options" do + @helper.options[:hello].should == 'world' + @helper.options[:foo].should == 'booze' + @helper.options[:wtf].should == 'dude' + @helper.raw_options.should_not have_key(:hello) + end + + it "should create option_accessors" do + @helper.hello.should == 'world' + @helper.hello('woooo') + @helper.hello.should == 'woooo' + end + +end + +class OptionsHelper + include Redistat::Options + + option_accessor :hello + + def default_options + { :hello => 'world', + :foo => 'bar' } + end + + +end \ No newline at end of file