Ruby class declaration issue

in ruby ​​you can:

class ApplicationController < ActionController::Base
  before_filter :require_login
end

I'm just wondering what is before_filter? Is this a method from ActionController :: Base?

and what happens if I create an ApplicationController object? Will the before_filter method run?

thank!

+3
source share
4 answers

Yes, it before_filteris a method on ActionController :: Base. Everything that is specified in before_filterwill be executed before the action (s) are called.

API documentation: http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000316

EDIT:

When you write directly to a class, this code is executed when the class is loaded into the interpreter.

Putting this into the IRB:

>> class Hello
>> p "hello"
>> end
"hello"

, , before_filter, . , , Object. ActionController:: Base before_filter, , .

>> ActionController::Base.class
=> Class
>> ActionController::Base.class.superclass
=> Module
>> ActionController::Base.class.superclass.superclass
=> Object
>> ActionController::Base.class.superclass.superclass.superclass

, MetaProgramming Ruby, , .

+8

, :

class ApplicationController
  self.before_filter
end

self (, try puts self )

,

class Filterable

    @@filters = []

    def self.before_filter(method_name)
      @@filters << method_name
    end

    def self.filters
      @@filters
    end

    def some_important_method
      self.class.filters.each do |method_name|
        # Halt execution if the return value of one of them is false or nil
        return unless self.send(method_name)
      end
      puts "I'm in some important method"
      # Continue with method execution
    end

end

class SomeClass < Filterable

  before_filter :first_filter
  before_filter :second_filter

  attr_accessor :x

  def initialize(x)
    @x = x
  end

  def first_filter
    puts "I'm in first filter"
    true
  end

  def second_filter
    puts "I'm in second filter"
    @x > 5
  end

end

SomeClass.new(8).some_important_method
# => I'm in first filter
#    I'm in second filter
#    I'm in some important method

SomeClass.new(3).some_important_method
# => I'm in first filter
#    I'm in second filter

,

+3

, ruby ​​ "".

. - .

, , :

class MyClass
  print "wow"
end

, "wow" nil.

: , , . , .

, before_filter. , " require_login ".

+2

. Ruby "", ruby, . before_filter .

0

Source: https://habr.com/ru/post/1754334/


All Articles