Skip to content

Instantly share code, notes, and snippets.

@ifyouseewendy
Last active August 29, 2015 14:06
Show Gist options
  • Save ifyouseewendy/cfa55635d52983e68379 to your computer and use it in GitHub Desktop.
Save ifyouseewendy/cfa55635d52983e68379 to your computer and use it in GitHub Desktop.
How to make method in module override the method in base class?
module A
  def foo
    puts 'foo from A'
    super
  end
end

module B
  def foo
    puts 'foo from B'
    super
  end
end

class Base
  include A, B

  def foo
    puts 'foo from Base'
  end
end

Base.new.foo
# => foo from Base

One way to solve is to use prepend instead of include, introduced by Ruby 2.0.

Considering the compatibility, Rails may not start to use it. Here is the Rails way to solve

module A
  def foo
    puts 'foo from A'
    super
  end
end

module B
  def foo
    puts 'foo from B'
    super
  end
end

class Metal
  def foo
    puts 'foo from Base'
  end
end

class Base
  include A, B
end

Base.new.foo
# => foo from A
# => foo from B
# => foo from Base
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment