Is there an elegant way to "continue if success" in Ruby? Something like this:
method1(a, b)
.and_then(method2)
.and_then(method3)
.fail { |x| 'something is wrong'}
I don't believe there is a way to do it exactly how you have shown, however you could use a begin and rescue block instead.
So the code would look like this:
begin
method1(a,b).method2.method3
rescue
p "something is wrong"
end
In any of the three methods, you should raise some sort of exception, simply by calling
raise "Something is Wrong"
and this will stop execution and run the rescue block. If you want to get some sort of data from the execution context where the raise call happened, you will need to implement your own type of error or use the existing types. If you wish to do this the rescue statement would need to be changed as follows
rescue => e
or if you have a type
rescue ArgumentError => e
This is a bit complex so at good article can be found here
This will only work if the methods you call actually raise exceptions.
Using tap you can “tap into” a method chain, in order to perform operations on intermediate results within the chain. Inside the tap block you can place your conditions.
method1(a, b).tap{|o| o.method2 if cond1}.tap{|o|o.method3 if cond2}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With