Search code examples
rubymodulemixins

NoMethodError: undefined method `meow?' for # - ruby mixin failing?


I'm playing with some of the very basics of ruby mixins, and for some reason can't access behavior from my module.

Running this on Ruby Fiddle:

module Cats
  MEOW = "meow meow meow"

  def Cats.meow?
    return Cats::MEOW
  end
end

class Example
  include Cats

  def sample
    return "it's a sample"
  end
end

e = Example.new
puts e.sample
puts e.meow?

This keeps returning NoMethodError: undefined method 'meow?' for #

My understanding of how mixins should work from tutorialspoint makes me feel like I should be able to validly call e.meow?, and get back the same result I would get from calling Cats.meow?.

Here's the code in RubyFiddle.

Incredibly basic, but any ideas where I'm falling down here?


Solution

  • As it turns out, I was being overly specific when defining Cats.meow?. If you want to use a module as a mixin you'll want to define your methods more generally, not with respect to their specific module namespace.

    So instead of

    def Cats.meow?
      ...
    end
    

    it should have been

    def meow?
      ...
    end 
    

    This lets you call e.meow?, since the method definition no longer limits it just to the Cats namespace.

    Whoops.