Skip to content

Instantly share code, notes, and snippets.

@apeiros
Created July 1, 2012 18:53
Show Gist options
  • Save apeiros/3029233 to your computer and use it in GitHub Desktop.
Save apeiros/3029233 to your computer and use it in GitHub Desktop.
Failure of `extend self`
require 'ostruct'
module Normalizer
extend self
def trim(str)
str.strip
end
end
obj = OpenStruct.new
obj.extend Normalizer
obj.trim = 'You must trim 5 spaces!'
obj.trim # fails, because it's hitting Normalizer#trim, wouldn't happen with module_function
@thatrubylove
Copy link

BOOM! It does work, you are attempting to mix this the wrong way.

>> module Normalizer
>>     extend self
>>     def trim(str)
>>         str.strip
>>       end
>>   end
=> nil

>> module TestModule
>>   def trim(str)
>>     "NOPE!"
>>     end
>>   end
=> nil
>> Normalizer.extend TestModule
=> Normalizer
>> Normalizer.trim("ok")
=> "NOPE!"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment