Pregunta

I'm going over the Ruby Bits course on Code School, and on level 5 they cover Modules.

On the hook methods part there's a certain challenge to add a self.included method hook for the LibraryUtils module which will extend the ClassMethods on the passed in class. The code follows:

module LibraryUtils

  def add_game(game)
  end

  def remove_game(game)
  end

  module ClassMethods
    def search_by_game_name(name)
    end
  end
end

class AtariLibrary
  include LibraryUtils
  extend LibraryUtils::ClassMethods
end

Very simple and easy. First just include the said method in our module, like so:

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

And then just take out the extend so we wont have duplicity.

The problem is, when I try this outside of the codeschool environment (browser) with Ruby 2.0 I get a No Method Error:

atari_library.rb:27:in `<main>': undefined method `search_by_game_name' for #<AtariLibrary:0x2b07ef8> (NoMethodError)

Keep in mind here that I am using the same code.

Well, if anyone have any thoughts on this, I'd greatly appreciate it.

¿Fue útil?

Solución

The only thing I can think of here that you're doing wrong is calling search_by_game_name on an instance of the AtariLibrary rather than the class, e.g:

AtariLibrary.search_by_game_name('name') # => works

al = AtariLibrary.new
al.search_by_game_name('name') # undefined method `search_by_game_name' for #<AtariLibrary:0x007fe3e204ebb0> (NoMethodError)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top