# app/controllers/demo_controller.rb classDemoController < ApplicationController deftest render :json => {msg:'this msg explains why this is a bad request'}, :status => :bad_request end end
# 进入 rails console
# case1: 不用块 [23] pry(main)> RestClient.post("localhost:3000/demo", {}) # => nil # RestClient::BadRequest: 400 Bad Request # from /Users/lijunwei/.rvm/gems/ruby-2.6.3@api-provider/gems/rest-client-2.1.0/lib/restclient/abstract_response.rb:249:in `exception_with_response'
# case2: 用块 [24] pry(main)> RestClient.post("localhost:3000/demo", {}) {|response, request, result| puts "response.body: #{response.body}\nrequest.body: #{request.args}\nresult.body: #{result.body}"} # => nil # response.body: {"msg":"this msg explains why this is a bad request"} # request.body: {:method=>:post, :url=>"localhost:3000/demo", :payload=>{}, :headers=>{}} # result.body: {"msg":"this msg explains why this is a bad request"}
# Return the default behavior corresponding to the response code: # # For 20x status codes: return the response itself # # For 30x status codes: # 301, 302, 307: redirect GET / HEAD if there is a Location header # 303: redirect, changing method to GET, if there is a Location header # # For all other responses, raise a response exception # defreturn!(&block) case code when200..207 self when301, 302, 307 case request.method when'get', 'head' check_max_redirects follow_redirection(&block) else raise exception_with_response end when303 check_max_redirects follow_get_redirection(&block) else raise exception_with_response end end
defexception_with_response begin klass = Exceptions::EXCEPTIONS_MAP.fetch(code) rescue KeyError raise RequestFailed.new(self, code) end
[20220613 update] better use robocop auto-correct to handle this issue. [20220728 update] bundle exec rubocop -A **/*.rb --only Style/FrozenStringLiteralComment
I’ve read a blog post written by Mike Perham introducing the Magic Comment, and I tried it out in my project.
The # frozen_string_literal: true
STEP-1: add this “magic comment”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Find all ruby files. # Iterate through them. # Add two lines if the file doesn't have those magic comment.
A space–time Tradeoff or time–memory trade-off in computer science is a case where an algorithm or program trades increased space usage with decreased time.
Here, space refers to the data storage consumed in performing a given task (RAM, HDD, etc), and time refers to the time consumed in performing a given task (computation time or response time).