Created
July 27, 2010 01:12
-
-
Save zerowidth/491553 to your computer and use it in GitHub Desktop.
module methods and super
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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