Question

How can I fix this error? I want to DRY my controller, and in each method I perform a sanity check on params[], just making sure all params are present.

The problem is with lambda's return. As it is defined

def validate_input(parameters)
    return proc {
        if parameters.find_index { |i| i.nil? }
          error_message = {'Error' => 'Please fix some params'}.to_json
          render :json => error_message and return
        end
    }
  end

Then, inside my controller action I do:

def action
  ...
  validate_input([my_sane_id, my_other_param]).call
  ...
end

And get the error: unexpected return.

Was it helpful?

Solution

def validate_input(*parameters)
  if parameters.any?(&:nil?)
     render :json => { :error => 'Please fix some params' }
     false
  else
     true
  end
end


def action
  ...
  return unless validate_input(my_sane_id, my_other_param)
  ...
end
  1. you can use the splat operator ("*") to get unknown number of parameters into array

  2. you can use ("any?") method instead of index (which is location)

  3. you can use symbol to proc ("&:") if you only making the function call on each item in array

  4. you dont need to call to_json if you render json

  5. better use symbol as hash key (":error")

  6. you return true/false to indicate if everything ok, and if its false, just return from the action

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top