The simple way to print exceptions in Ruby

How to use rescue

# catch most exceptions (anything that derives from StandardError)
begin
  ...
rescue
  puts $!, $@
end

# catch all exceptions (anything that derives from Exception)
begin
  ...
rescue Exception
  puts $!, $@
end

begin
  ...
rescue Exception => ex
  puts ex.message
  puts ex.backtrace.join("n")
end

rescue
  p $!
  puts $@
end

# or

rescue
  puts $!.inspect, $@
end

Reference

https://coderrr.wordpress.com/2008/11/07/the-simple-way-to-print-exceptions-in-ruby/

How to send mail by mandrillapp with Rails?

Official Site

https://mandrillapp.com/

RailsApps Tutorial

http://railsapps.github.io/rails-send-email.html

Rails Configuration

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address: 'smtp.mandrillapp.com',
  port: 587,
  user_name: 'your_mail_address@somewhere.com',
  password: 'any valid API key generated by mandrill'
}

So easy!

How to custom validators in Ruby on Rails 4?

Model

# app/models/contact_ticket.rb

class ContactTicket < ActiveRecord::Base
  validates :name, :my_email_field, :content, presence: true
  validates :my_email_field, email: true # <-- custom email validator

  # ...

end

Config

# config/application.rb

  # ...

  # add custom validators path
  config.autoload_paths += %W["#{config.root}/app/validators/"]

  # ...

Validator

# app/validators/email_validator.rb

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /A([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})z/i
      record.errors[attribute] << (options[:message] || "wrong email address")
    end
  end
end

Reference