I wrote a little gem today that will standardize your way of getting good responses back from your objects in Ruby. I called it HollaBack. The gem can be configured with extra options for custom status messages, and methods that will be ran so that information from those methods can be included in your response object.

Usage

Ponder the hypothetical class with HollaBack included that will be used for these examples:

some_class.rb

class SomeClass
  include HollaBack

  def truthy_method
    true
  end

  def falsey_method
    [nil, false].sample
  end

  def optional_method_with_params(condition=nil)
    condition ? true : false
  end

  def optional_method
    'some random info'
  end
end

Simple example:

klass = SomeClass.new

# Minimal request
response = klass.response(status_method: 'truthy_method')
# => #<HollaBack::Response>
response.successful?
# => true
response.status_message
# => "Status: successful"

With customized status messages:

# If we have a truthy status method
response = klass.response(status_method: 'truthy_method', success_message: "It worked! :D", failure_message: "It didn't work! D:")
# => #<HollaBack::Response>
response.successful?
# => true
response.status_message
# => "It worked! :D"

# If we have a falsy status method
response = klass.response(status_method: 'falsey_method', success_message: "It worked! :D", failure_message: "It didn't work! D:")
# => #<HollaBack::Response>
response.successful?
# => false
response.status_message
# => "It didn't work! D:"

With extra methods you need information from

response = klass.response(status_method: 'falsey_method', responding_methods: [:optional_method, {:optional_method_with_params => ['some param']}])
# => #<HollaBack::Response>
response.responding_methods
#=> {:optional_method =>"some random info", :optional_method_with_params=>true}

If you pass in a status method or some responding methods that raise exceptions, HollaBack will simply handle these gracefully, because exceptions are still a response from your code. The important one is your status message. If you want to force the error, then you call the successful? to force the exception on the status method, else you can check the responding object for the Exception.

With some method that totally doesn't exist

response = klass.response(status_method: 'some_method_that_totally_doesnt_exist')
# => #<HollaBack::Response>
response.responding_object
#=> NoMethodError
response.status_message
#=> "undefined method `some_method_that_totally_doesnt_exist' for #<SomeClass:0x00000001e1b008>"

David Chapman is a Ruby on Rails developer at isotope|eleven with over 5 years development experience. He's currently majoring in Electrical Engineering with a minor in Computer Science at the University of Alabama at Birmingham. David is a Linux geek, a math geek, a physics geek, a serious gamer, and a reader of Reddit. His super power is eating chips and salsa.