Ruby on Rails before_filter vs ruby's initialize

前端 未结 2 1319
忘了有多久
忘了有多久 2021-01-11 10:07

Just a thought in my mind. what is the difference the following

before_filter

class ApplicationController < ActionController::Bas         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-11 10:56

    I believe this was covered in Practical Object-Oriented Design in Ruby by Sandi Metz.

    Suppose you are designing a base class for other developers/users, and want to allow them to hook into various steps in a procedure (e.g. initialization.) In general, there are two ways:

    1. Break up the procedure into small methods, and (in the documentation) remind users to use super whenever they override a method.
    2. Include calls to various empty hook methods that users can override with custom functionality.

    (I believe that these are variations of the Template Method pattern.)

    The second way requires more effort on your part and less effort for your users.

    In this specific case, before_filter provides a cleaner way to attach multiple hooks and encourages you to break up hooks into single-responsibility methods with meaningful names. This becomes more important in applications that use more controller inheritance.

提交回复
热议问题