简体   繁体   中英

What is the difference between instance&class method include&extend (Ruby, Rails)

What's the difference between class method and instance method.

I need to use some functions in a helper "RemoteFocusHelper" (under app/helpers/)

Then include the helper "RemoteFocusHelper" in the Worker module

But when I tried to call 'check_environment' (defined in RemoteFocusHelper ),

It raised ""no method error"".

Instead of using "include", I used the "extend" and works.

I wonder know if it is correct that we can only use a class method when in a class method.

Is it possible to call a instance method in a class method ?

By the way,how does the rake resque:work QUEUE='*' know where to search the RemoteFocusHelper I didn't give it the file path.Is the rake command will trace all files under the Rails app?

automation_worker.rb


    class AutomationWorker
      @queue = :automation

      def self.perform(task=false)
        include RemoteFocusHelper
        if task
          ap task
          binding.pry
          check_environment
        else
          ap "there is no task to do"      
        end
      end
    end

The difference is the context where you're executing. Pretty much every tutorial will have include or extend under the class :

class Foo
  include Thingy
end

class Bar
  extend Thingy
end

This will get executed at the time the class is defined: self is Foo (or Bar ) (of type Class ). extend will thus dump the module contents into self - which creates class methods.

When you do it inside a method definition, self is the instance object (of type Foo or Bar ). Thus the place where the module gets dumped into changes. Now if you extend (the module contents), it dumps them into what is now self - resulting in instance methods.

EDIT: It is also worth noting that because extend works on any instance object, it is defined on Object . However, since only modules and classes are supposed to be able to include stuff, include is an instance method of Module class (and, by inheritance, Class as well). As a consequence of this, if you try putting include inside a definition of an instance method, it will fail hard, since most things (including your AutomationWorker ) are not descended from Module , and thus do not have access to the include method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM