Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

better delegate decorator

  • Loading branch information...
commit 089632ee637551b269b4b6839a652c8ab6ad3496 1 parent dcd0463
@kristianmandrup authored
Showing with 43 additions and 4 deletions.
  1. +14 −4 lib/sugar-high/delegate.rb
  2. +29 −0 spec/sugar-high/delegate_spec.rb
View
18 lib/sugar-high/delegate.rb
@@ -41,11 +41,21 @@ def #{prefix}#{method}(*args, &block)
# http://blog.jayfields.com/2008/02/ruby-replace-methodmissing-with-dynamic.html
class DelegateDecorator
- def initialize(subject)
- subject.public_methods(false).each do |meth|
+ def initialize(subject, options = {})
+ options[:only] ||= []
+ options[:except] ||= []
+ options[:only].map!(&:to_s)
+ options[:except].map!(&:to_s)
+
+ meths = subject.public_methods(false)
+ meths = meths & options[:only] unless options[:only].empty?
+
+ meths.each do |meth|
(class << self; self; end).class_eval do
- define_method meth do |*args|
- subject.send meth, *args
+ unless options[:except].include? meth.to_s
+ define_method meth do |*args|
+ subject.send meth, *args
+ end
end
end
end
View
29 spec/sugar-high/delegate_spec.rb
@@ -17,3 +17,32 @@ def actor
describe 'delegate NOT already defined' do
specify { Context.new.act.should == 'actor' }
end
+
+class SuperRange < DelegateDecorator
+ attr_accessor :range
+
+ def initialize range
+ super(range, except: ['to_s', 'to_str'])
+ @range = range
+ end
+
+ def to_s
+ "Super: #{range}"
+ end
+
+ def to_str
+ to_s
+ end
+end
+
+describe DelegateDecorator do
+ subject { SuperRange.new (0..2) }
+
+ specify {
+ subject.to_s.should == "Super: 0..2"
+ subject.to_str.should == "Super: 0..2"
+ }
+
+ specify { subject.min.should == subject.range.min }
+ specify { subject.max.should == subject.range.max }
+end
Please sign in to comment.
Something went wrong with that request. Please try again.