Search code examples
ruby-on-railsrubyjsonrescue

Rescue From If JSON


I'd like to rescue from a RecordNotFound exception if, and only if, the request is JSON. Now if I was doing this for a skip_before_action, I would do the below:

skip_before_action :verify_authenticity_token, if: :json_request?

Is there syntax for this in rescue_from? Something like:

rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found, if: :json_request?

Helper method:

protected
  def json_request?
    request.format.json?
  end

Solution

  • I am assuming if the request is not JSON then you want to raise? If so you should be able to do this

    rescue_from ActiveRecord::RecordNotFound { request.format.json? ? record_not_found : super }
    

    OR

    rescue_from ActiveRecord::RecordNotFound, with: lambda{|e| request.format.json? ? record_not_found(e) : raise(e) }
    

    These will have identical impact because if a block is given it assigns it to the options[:with] where as if with: is supplied it uses this as the block and ignores any other block passed to it

    rescue_from takes a splat argument called *klasses and a block. It then parses *klasses to determine the options passed in of which it only cares about :with. It then applies the :with block to the key(s) which will represent exception class names to handle.

    There is no additional options that will be acknowledged.

    Please be advised I have not tested this