Skip to content

Instantly share code, notes, and snippets.

@armw4
Last active December 31, 2015 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armw4/8000907 to your computer and use it in GitHub Desktop.
Save armw4/8000907 to your computer and use it in GitHub Desktop.
Ruby is such an incredible programming language. One of the cool things I like about it is mixins. You can declaratively add behavior to a class in a very ad-hoc manner. It's so cool....again! One great opportunity I can think of for mixins is when you need to opt out of a base class's functionality in a very DRY (Do No Repeat Yourself...aka...n…

###by Antwan Wimberly###

class Base
  def print_value(value)
    puts value.to_s
  end
end

class DerivedClass < Base; end

DerivedClass.new.print_value(99) # => 99

# we'll use this bag of functionality to override the parent in a consistent way
module CustomPrint
  def print_value(value)
    count_to_ten = proc {
      1.upto(10) { puts "counting to 10." }
    }
    count_to_ten.call
  end
end

# this guy needs to do more than just print a value...he needs to count to 10
class CountToTen < Base
  include CustomPrint
end

CountToTen.new.print_value(99) # => counting to 10.
                               # => counting to 10.
                               # => counting to 10.
                               # => ....7 more times

# but what if for some strange reason I wanted to have the best of both worlds?
class BestOfBoth < Base
  extend CustomPrint

  def print_value(value)
    super
    # we could also call BestOfBoth.print_value(value)
    self.class.print_value(value)
  end
end

BestOfBoth.new.print_value(99) # => 99
                               # => counting to 10.
                               # => counting to 10.
                               # => counting to 10.
                               # => ....7 more times
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment