Richlewis
Richlewis

Reputation: 15374

Inheriting module/class methods

I have this module with a method:

module MySqlConnection
  def database_connect(application)
    # Code in here
  end
end

I have a second module with a class that uses database_connect:

module ResetPopups
  class PopupsOff
    include MySqlConnection
    def self.reset_popup
      database_connect("#{APP}")
    end
  end
end

When I call:

ResetPopups::PopupsOff.reset_popup

I get an undefined method database_connect. Why does this happen?

Upvotes: 2

Views: 52

Answers (2)

Marek Lipka
Marek Lipka

Reputation: 51151

include adds module methods as instance methods, while extend adds them as singleton methods. Since you want to use this in the context of class (singleton context), you need to use extend:

extend MySqlConnection

Upvotes: 5

Andrey Deineko
Andrey Deineko

Reputation: 52357

module ResetPopups
  class PopupsOff
    extend MySqlConnection
    def self.reset_popup
      database_connect("#{APP}")
    end
  end
end

would work

What is hapening here, is that you include MySqlConnection, which makes method defined in it (database_connect) instance methods. But you use this module in the class scope, calling the database_connect on the class.

Upvotes: 3

Related Questions