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

- old
+ new

@@ -4,33 +4,46 @@ def self.included base base.const_set :OptionInitializing, Class.new { attr_reader :options alias to_h options + const_set :VALIDATORS, [] + def initialize base, options + validate options @base = base @options = options end def new *args, &block args = args.dup opts = @options # Convention. Deal with it. if args.last.is_a?(Hash) + validate args.last args[-1] = opts.merge(args.last) else args << opts.dup end @base.new(*args, &block) end def merge opts + validate opts self.class.new @base, @options.merge(opts) end + def validate hash + self.class.const_get(:VALIDATORS).each do |validator| + hash.each do |k, v| + validator.call k, v + end + end + end + def method_missing sym, *args, &block # 1.8 if @base.instance_methods.map(&:to_sym).include?(sym) @base.new(@options.dup).send sym, *args, &block else @@ -39,13 +52,21 @@ end } unless base.constants.map(&:to_sym).include?(:OptionInitializing) base.class_eval do class << self - if method_defined?(:option_initializer) - undef_method(:option_initializer) + [:option_initializer, :option_validator].each do |m| + undef_method(m) if method_defined?(m) end end + + def base.option_validator &block + raise ArgumentError, "block must be given" unless block + raise ArgumentError, "invalid arity (expected: 2)" unless block.arity == 2 + oi = self.const_get(:OptionInitializing) + oi.const_get(:VALIDATORS).push block + end + def base.option_initializer *syms oi = self.const_get(:OptionInitializing) # Class methods syms.each do |sym|