What does #self.included(base) do in Ruby on Rails' Restful Authentication?

后端 未结 5 1936
离开以前
离开以前 2021-01-30 03:50

I thought we would do

helper_method :current_user, :logged_in?, :authorized?

to make these controller methods available for use as helper metho

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-30 04:33

    Out of the same reason which Peter has mentioned I would like to add an example so that it's easy for the newbie developers to understand self.included(base) and self.extended(base) :

    module Module1
     def fun1
        puts "fun1 from Module1"
     end
    
     def self.included(base)
        def fun2
            puts "fun2 from Module1"
        end
     end
    
     def self.extended(base)
       def fun3
         puts "fun3 from Module1"
       end
     end
    
    end
    
    module Module2
     def foo
        puts "foo from Module2"
     end
    
     def self.extended(base)
        def bar
            puts "bar from Module2"
        end
     end
    end
    
    
    class Test
    include Module1
    extend Module2
     def abc
        puts "abc form Test"
     end
    end
    
    class Test2
      extend Module1
    end
    

    Test.new.abc #=> abc form Test

    Test.new.fun1 #=> fun1 from Module1

    Test.new.fun2 #=> fun2 from Module1

    Test.foo #=> foo from Module2

    Test.bar #=> bar from Module2

    Test.new.fun3 #=> NoMethodError (undefined method `fun3' ..)

    Test2.fun3 #=> fun3 from Module1

    extend : methods will be accessible as class methods

    include : methods will be available as instance methods

    "base" in self.extended(base) / self.included(base) :

    The base parameter in the static extended method will be either an instance object or class object of the class that extended the module depending whether you extend a object or class, respectively.

    When a class includes a module the module’s self.included method will be invoked. The base parameter will be a class object for the class that includes the module.

提交回复
热议问题