Skip to content

Instantly share code, notes, and snippets.

@zerowidth
Created July 27, 2010 01:12
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 zerowidth/491553 to your computer and use it in GitHub Desktop.
Save zerowidth/491553 to your computer and use it in GitHub Desktop.
module methods and super
# A rough example of how I'm putting module method overrides to use.
# This allows me to add functionality to methods without having to
# do method aliasing, and it's easy to enable/disable things too.
module Search
def search(query, opts={})
request("search", :query => query).results
end
end
# this is where the module method override comes in:
module Retry
def search(query, opts={})
should_retry = opts.delete(:retry_forever)
begin
super query, opts
rescue ClientError
if should_retry
sleep rand
retry
else
raise
end
end
end
end
class Client
def request(params)
# http request against the server, basic response handling, etc
end
include Search # search requests using request method
include Retry # retry logic for search requests
end
client = Client.new
# get some search results
client.search("foo")
# get some search results, this time retrying on failure
client.search("foo", :retry_forever => true)
# super in modules demo: with care, this can be powerful.
module Debug
def no_override(*args)
puts "debug: fails called with #{args.inspect}"
super
end
def hello(*args)
puts "debug: calling hello"
super
end
def out_of_order(*args)
puts "debug: out of order inclusion"
super
end
end
module Hello
def hello(name)
puts "hello, #{name}!"
end
end
module OutOfOrder
def out_of_order(name)
puts "#{name}! you're out of order!"
end
end
class Greeter
def no_override(name)
puts "sorry, #{name}, this doesn't get debugging"
end
include Hello
include Debug
include OutOfOrder
end
g = Greeter.new
g.no_override("world")
g.hello("world")
g.out_of_order("world")
# $ ruby super_modules.rb
# sorry, world, this doesn't get debugging
# debug: calling hello
# hello, world!
# world! you're out of order!
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment