RubyでPHPのエラー制御演算子(@演算子)のようなもの

PHPにはエラー制御演算子(@演算子) というものがあり、 たとえば下記のようにすることで例外が発生しなくなります。

$str = @file_get_content('hoge.txt'); // hoge.txtが存在しなくても例外は発生しない。

Rubyでも同じことをやろうと思った場合、 rescue をワンライナーで書けば実現可能です。

str = File.read('hoge.txt') rescue nil

ただし、RuboCopでは警告が発生するので、 Style/RescueModifier のルールを無効にする必要があります。

もちろん、プロダクトコードでは使用すべきではないですが、RSpec等では役に立つと思います。
たとえば以下のような感じです。

テスト対象のコード

require 'pg'

class Sample
  class << self
    PARAM = {
      host: 'localhost',
      user: 'user',
      database: 'dbname',
      port: '5432',
      password: 'password'
    }.freeze

    def get
      conn = nil
      begin
        conn = PG::Connection.new(PARAM)
        conn.exec('SELECT * FROM users')
      ensure
        conn&.close
      end
    end
  end
end

テストコード

describe Sample do
  describe 'get' do
    subject(:get) { described_class.get }

    let(:connection) { instance_double('connection') }

    before do
      allow(PG::Connection).to receive(:new).and_return(connection)
      allow(connection).to receive(:exec).and_raise(PG::Error)
      allow(connection).to receive(:close)
    end

    context '例外発生時' do
      it 'closeが呼ばれること' do
        # ↓関数の実行だけ行い、
        get rescue nil # rubocop:disable Style/RescueModifier
        # ↓PG::Connection.close が呼ばれたかを確認する。
        expect(connection).to have_received(:close).once
      end
    end
  end
end