Cấu hình SSL của Ruby on Rails

Michael Gorsuch đăng bài về cách nhanh chóng thiết lập ứng dụng Ruby on Rails của bạn để sử dụng SSL.

I was trying to think up the “Ruby Way” to add SSL support to AreYouHiring.com for credit card payments. I surprised myself with this one.

Assuming that you already have an SSL cert installed for your app, add the following to your application.rb under app/controllers:

def require_ssl
    redirect_to :protocol => "https://" unless (request.ssl? or local_request?)  
  end

Now, we just need to add a before_filter for the actions that need it. I opened up my Job controller, and added the following line:

before_filter :require_ssl, :only => [:preview, :card_payment]

To test this stuff out, I built the following functional tests for my Job controller:

def test_preview
    request.env[‘HTTPS’] = ‘on’
    get :preview, :id => jobs(:first).id

    assert_response :success
    assert @request.ssl?   
    assert assigns(:job).valid?
    assert assigns(:payment)
  end

  def test_preview_without_ssl
    get :preview, :id => jobs(:first).id
    assert_response :redirect
    assert_redirected_to :protocol => “https://”
  end

For brevity’s sake, I am only showing the code that tests the ‘preview’ action of the Job controller. Notice that I built one test to hit the action with SSL, which should function as normal, and another to hit the action without it.

So there you go, SSL in just a few minutes. It still amazes me how much you can get done in no time with the Ruby on Rails framework.

Tạm hiểu như sau:

Ông ta muốn cho các khoản thanh toán bằng thẻ tín dụng có hỗ trợ  SSL  vào AreYouHiring.com.  Giả sử rằng bạn đã cài đặt chứng chỉ SSL cho ứng dụng của mình, hãy thêm thông tin sau vào application.rb của bạn trong app / controller:

def require_ssl
    redirect_to :protocol => "https://" unless (request.ssl? or local_request?)  
  end

Thêm before_filter cho các hành động cần nó.

before_filter: request_ssl,: only => [: preview,: card_payment]

Xây dựng các bài kiểm tra chức năng sau:

def test_preview
    request.env[‘HTTPS’] = ‘on’
    get :preview, :id => jobs(:first).id

    assert_response :success
    assert @request.ssl?   
    assert assigns(:job).valid?
    assert assigns(:payment)
  end

  def test_preview_without_ssl
    get :preview, :id => jobs(:first).id
    assert_response :redirect
    assert_redirected_to :protocol => “https://”
  end
0/5 (0 Reviews)

Leave a Comment