Skip to content

Instantly share code, notes, and snippets.

@elainenaomi
Last active December 18, 2018 15:35
Show Gist options
  • Save elainenaomi/e7d92688629ef2ddc9cce7084fb74d29 to your computer and use it in GitHub Desktop.
Save elainenaomi/e7d92688629ef2ddc9cce7084fb74d29 to your computer and use it in GitHub Desktop.
Status Object (from Confident Ruby)

Status object definition:

class ImportStatus
  def self.success() new(:success) end
  def self.redundant() new(:redundant) end
  def self.failed(error) new(:failed, error) end

  attr_reader :error

  def initialize(status, error=nil)
    @status = status
    @error = error
  end
  def success?
    @status == :success
  end
  def redundant?
    @status == :redundant
  end
  def failed?
    @status == :failed
  end
end

Setting the status:

def import_purchase(date, title, user_email)
  user = User.find_by_email(user_email)
  if user.purchased_titles.include?(title)
    ImportStatus.redundant
  else
    purchase = user.purchases.create(title: title, purchased_at:
      date)
    ImportStatus.success
  end
rescue => error
  ImportStatus.failed(error)
end

Checking the returned status:

result = import_purchase(date, title, user_email)
if result.success?
  send_book_invitation_email(user_email, title)
elsif result.redundant?
  logger.info "Skipped #{title} for #{user_email}"
else
  logger.error "Error importing #{title} for #{user_email}:
  #{result.error}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment