Tham khảo tài liệu 'ruby for rails phần 10', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | Incorporating customer signup and login 441 The importance depends on the action We don t want unauthorized access to sensitive actions. But even for harmless actions like viewing the catalogue or the welcome screen we still want to know whether a known person is logged in so we can greet the person by name not bother displaying the login form and so forth. All of this can be accomplished with the help of a hook or callback facility called beforefilter. Gate-keeping the actions with before_filter The kind of gate-keeping called for here examining the state of affairs with regard to the visitor after an action has been requested but before it s been exe-cuted is accomplished with the use of special hooks particularly a class method called before_filter. This method is an overseer You give it as arguments in symbol form the names of instance methods that you wish to be run before one or more actions are run. Even though some actions aren t particularly security-sensitive like viewing the welcome screen you always want to know whether someone is logged in and you want to know who it is. To accomplish this you add code to the generic controller file . This file contains a class definition class Applicationcontroller ActionController Base end If you look at any other controller file say you ll see that the controller class in that file inherits from ApplicationController class Composercontroller Applicationcontroller end You can put calls to before_filter in any controller file. But if you put them in the filters you set up are called along the way to any action in any controller file. Let s set up a filter that will always be executed whenever anyone sends in a request for any controller action at all. Listing shows such an arrangement. Listing Filtering all incoming requests with before_filter class ApplicationController ActionController Base layout base before_filter get_customer B def .