Skip to content

Instantly share code, notes, and snippets.

@TheKidCoder
Created December 15, 2015 16:18
Show Gist options
  • Save TheKidCoder/402b7e77aae48a3da34d to your computer and use it in GitHub Desktop.
Save TheKidCoder/402b7e77aae48a3da34d to your computer and use it in GitHub Desktop.
class Thinger
def run!
[:first_thing, :second_thing, :third_thing].map do |meth_name|
begin
self.method(meth_name).call
rescue => e
puts "There was a problem running: #{meth_name}"
next
end
end
end
def first_thing
puts "I'm the first to go!"
end
def second_thing
raise StandardError, "Oh no!"
end
def third_thing
puts "Last to finish!"
end
end
@yez
Copy link

yez commented Dec 15, 2015

Why the next on line 9? Without it, the code will continue to the next element in the array automatically, it seems redundant.

@tom-lord
Copy link

  • Why is run! a bang method?
  • Why is the list: [:first_thing, :second_thing, :third_thing] hard-coded? That could be a parameter.
  • Why self.method(meth_name).call? Rather than just send meth_name
  • Why next, at all?

Also, if you're in a Rails project (or don't mind explicitly requiring activesupport/lib/active_support/core_ext/object/try.rb), then this is basically already built-in:

def foo
  raise "AAAAHHHH"
end
foo
  => RuntimeError: AAAAHHHH 
try(:foo)
   => nil

@tom-lord
Copy link

I.e. you could just do something like

def try_list(*methods)
  methods.each do |m|
    try(m) || puts "There was a problem running: #{m}"
  end
end

try_list(:first_thing, :second_thing, :third_thing)

@TheKidCoder
Copy link
Author

  • It's a bang method because it's a stylistic choice that I use when I don't have an explicit return value. In this case, I would usually return true/false here.
  • It's hard coded because this can be seen more as a service object. I don't really understand this question anyway, at some point in the code, there will be a hard-coded list.
  • I dislike send. If anything, public_send is better and using this method you can do other things, (maybe a conditional on the arity of the method).
  • I'm not in the implicit return camp. Likewise, I like to be explicit about what an iterator is doing when catching an error. Just stylistic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment