简体   繁体   中英

Extend and Include

Rubymonk 4.1 entitled "The included Callback and the extend Method" is asking me to modify the module Foo in the following exercise so that when you include it in the class Bar, it also adds all the methods from ClassMethods into Bar as class methods.

module Foo
  module ClassMethods
    def guitar
      "gently weeps"
    end
  end
end

class Bar
  include Foo
end

puts Bar.guitar

Must define self.included(base) method in the module and extend the base with ClassMethods.

I've been tinkering around and can't figure it out.

Guidance please :D

You define a method called self.included(base) .

module Foo
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods    
    def hey
      p "hey!"
    end
  end
end

class Bar
  include Foo
end

puts Bar.hey #=> hey!

This works because .included is called anytime a module is included. Inside .included your code is extending the base class with the methods from ClassMethods .

John Nunemaker has an excellent post with details here:

Include vs Extend in Ruby .

See the bottom of the post for the answer to this question in greater detail. It's a great read.

module Foo
  def self.included(base)
    base.extend Foo::ClassMethods
  end

  module ClassMethods    
    def guitar
      "gently weeps"
    end
  end
end

class Bar
  include Foo
end

puts Bar.guitar

You need to use ActiveSupport::Concern http://api.rubyonrails.org/classes/ActiveSupport/Concern.html

module Foo
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def guitar
      "gently weeps"
    end
  end
end

class Bar
  include Foo
end

puts Bar.guitar

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