|
class Foo |
|
extend HandleWithCare |
|
def func(*args, &block) |
|
if block |
|
block.call(*args) if block |
|
elsif args.any? |
|
args.join(' ') |
|
else |
|
'no args' |
|
end |
|
end |
|
public :eval |
|
handle_with_care :func |
|
end |
|
|
|
describe HandleWithCare do |
|
describe '::handle_with_care' do |
|
shared_examples_for 'a method handled carefully' do |*args, &block| |
|
def build_method_call(method_name, args, block) |
|
eval_me = "send \"#{method_name}\"" |
|
eval_me << ', *args' if args.any? |
|
eval_me << ', &block' if block |
|
eval_me |
|
end |
|
let(:method_name) { :func } |
|
let(:method_call) {build_method_call method_name, args, block} |
|
let(:original_method_call) {build_method_call "original_#{method_name}", args, block} |
|
|
|
it 'without the prefix, raises an error' do |
|
expect { Foo.new.eval method_call }.to raise_error(RuntimeError, 'You have called a dangerous method. Please call the method with your args prepended with {forced: true} if you did this on purpose') |
|
end |
|
|
|
it 'with the prefix, calls the original function' do |
|
original_result = Foo.new.eval(original_method_call) |
|
|
|
args.unshift({force: true}) |
|
Foo.new.eval(method_call).should == original_result |
|
end |
|
end |
|
|
|
context 'method with no arguments' do |
|
it_behaves_like 'a method handled carefully' |
|
end |
|
|
|
context 'method with arguments' do |
|
it_behaves_like 'a method handled carefully', 'some', 'args' |
|
end |
|
|
|
context 'method with a block' do |
|
it_behaves_like('a method handled carefully') {'a block'} |
|
end |
|
|
|
context 'method with args and a block' do |
|
it_behaves_like('a method handled carefully', 'args', 'and') {|a, b| "#{a} #{b} a block"} |
|
end |
|
end |
|
end |