Rails - Break Statement?
Does rails have开发者_高级运维 a break statement?
I'm writing a controller that has some pretty complicated IF statements. In Sum what I'd like to do is something like this:
IF !All these variable exist and are not nil? BREAK and don't continue bec something went wrong END
If XXX = 'adsasd do all this stuff ELSE IF
ELSE send out an error email
Is a break possible?
I don't know when all of your variables become available, but when I want to do checks in the controller, I usually use the before_filter callbacks to do that. For example:
class YourController
before_filter :check_if_variables_exist
def show
#prepare for render view
end
private
def check_if_variables_exist
unless @your_variable.nil?
#Do what you want
render :nothing => true
end
end
What this does is that when a request comes to action show in YourController, it will first call the private method check_if_variables_exist. If @your_variable is nil than it will end up at render :nothing => true and the filter_chain will be halted and the action show will never be called. If however your_variable is not nil, then the method will end without doing anything and the controller will then call the action show like usual.
So all the things you want to check beforehand can be placed in different before_filter callbacks. And if you don't want the check for all actions in the Controller, it can be specified like this:
class YourController
before_filter :first_check, :only => [:index, :show]
before_filter :second_check, :only => [:show, :edit]
In my opinion, this is the "rails" way to do it.
Ruby's return
statement is what you're looking for. However...
I'm writing a controller that has some pretty complicated IF statements
Without knowing anything else about your application, this is a BIG red flag. Controllers are not the place to have a bunch of complicated logic. If you're using RESTful design patterns (and there's rarely a reason not to), then your controllers should be very lightweight and contain almost no logic. Models are where your business logic belongs. They allow you to isolate logic, simplifying your application and making it easier to test.
精彩评论