Skip to content

Commit

Permalink
chaining multiple methods at once
Browse files Browse the repository at this point in the history
  • Loading branch information
rkh committed Mar 22, 2009
1 parent 93e699e commit d7c36a4
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion chainable.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |s|
s.name = "chainable"
s.version = "0.0.1"
s.version = "0.0.2"
s.authors = ["Konstantin Haase"]
s.date = "2009-03-20"
s.description = "never use alias_method_chain, again"
Expand Down
6 changes: 4 additions & 2 deletions lib/chainable.rb
Expand Up @@ -14,8 +14,9 @@ def self.skip_chain
# Maybe that is not what you want, as methods defined by def tend to be
# faster. If that is the case, simply don't pass the block and call def
# after chain_method instead.
def chain_method(name, &block)
name = name.to_s
def chain_method(*names, &block)
raise ArgumentError, "no method name given" if names.empty?
name = names.shift.to_s
if instance_methods(false).include? name
begin
code = Ruby2Ruby.translate self, name
Expand All @@ -27,6 +28,7 @@ def chain_method(name, &block)
end
block ||= Proc.new { super }
define_method(name, &block)
chain_method(*names, &block) unless names.empty?
end

# If you define a method inside a block passed to auto_chain, chain_method
Expand Down
11 changes: 11 additions & 0 deletions spec/chainable/chain_method_spec.rb
Expand Up @@ -60,6 +60,17 @@ def to_i
@an_instance.to_i.should == @original_results["to_i"] + 20
end

it "should allow passing multiple method names to chain_methdo" do
@a_class.class_eval do
chain_method :random, :foo2
chain_method(:foo, :to_i) { super.to_s }
end
@an_instance.random.should == @original_results["random"]
@an_instance.foo2.should == @original_results["foo2"]
@an_instance.foo.should == @original_results["foo"].to_s
@an_instance.to_i.should == @original_results["to_i"].to_s
end

it "should keep inheritance intact" do
a_module = Module.new do
define_method(:inspect) { "some inspect result" }
Expand Down

0 comments on commit d7c36a4

Please sign in to comment.