lib/option_initializer.rb in option_initializer-1.0.1 vs lib/option_initializer.rb in option_initializer-1.1.0

- old
+ new

@@ -9,22 +9,22 @@ def initialize base, options @base = base @options = options end - def new *args + def new *args, &block args = args.dup opts = @options # Convention. Deal with it. if args.last.is_a?(Hash) args[-1] = opts.merge(args.last) else args << opts.dup end - @base.new(*args) + @base.new(*args, &block) end def merge opts self.class.new @base, @options.merge(opts) end @@ -35,31 +35,58 @@ @base.new(@options.dup).send sym, *args, &block else raise NoMethodError, "undefined method `#{sym}' for #{self}" end end - } unless base.constants.include?(:OptionInitializing) + } unless base.constants.map(&:to_sym).include?(:OptionInitializing) base.class_eval do + class << self + if method_defined?(:option_initializer) + undef_method(:option_initializer) + end + end def base.option_initializer *syms oi = self.const_get(:OptionInitializing) # Class methods syms.each do |sym| self.class_eval do # define_singleton_method not available on 1.8 singleton = class << self; self end - singleton.send :define_method, sym do |v| - oi.new self, sym => v + singleton.send :undef_method, sym if singleton.method_defined?(sym) + singleton.send :define_method, sym do |*v, &b| + if b && v.empty? + oi.new self, sym => b + elsif b && !v.empty? + raise ArgumentError, + "wrong number of arguments (#{v.length} for 0 when block given)" + elsif v.length == 1 + oi.new self, sym => v.first + else + raise ArgumentError, + "wrong number of arguments (#{v.length} for 1)" + end end end end # Instance methods oi.class_eval do syms.each do |sym| - define_method(sym) do |v| - merge(sym => v) + undef_method(sym) if method_defined?(sym) + define_method(sym) do |*v, &b| + if b && v.empty? + merge(sym => b) + elsif b && !v.empty? + raise ArgumentError, + "wrong number of arguments (#{v.length} for 0 when block given)" + elsif v.length == 1 + merge(sym => v.first) + else + raise ArgumentError, + "wrong number of arguments (#{v.length} for 1)" + end end end end end end