Skip to content

Instantly share code, notes, and snippets.

@wycats
Forked from nkallen/MODULARITY_OLYMPICS.markdown
Created February 15, 2010 20:19
Show Gist options
  • Save wycats/304951 to your computer and use it in GitHub Desktop.
Save wycats/304951 to your computer and use it in GitHub Desktop.
module ParameterizedConcern
def extended(mod = nil, &block)
unless mod
@extended_block = block
return
end
mod.module_eval(&@extended_block) if @extended_block
end
def self.extended(mod)
class << mod
def with(options) define_method(:with_options) { options }; dup end
end
end
end
module Query
class Original
def initialize(connection, query_string, *args)
# Implement initialize
end
def select
# Implement select
end
end
module Timeouter
extend ParameterizedConcern
def select
Timeout.timeout(with_options[:duration]) do
super
end
end
end
module Memoizer
extend ParameterizedConcern
extended do
@query_memo ||= {}
end
def new(connection, query_string, *args)
@query_memo[[connection, query_string, args]] ||= super
end
end
end
class MyQuery < Query::Original
include Query::Timeouter.with(:duration => 5)
extend Query::Memoizer
end
class NewQuery < Query::Original
include Query::Timeouter.with(:duration => 10)
end
MyQuery.new("connection", "get me 1").select
MyQuery.new("connection", "get me 1").select
NewQuery.new("connection", "get me 1").select
NewQuery.new("connection", "get me 1").select
MyQuery.new("connection", "get me 1").select
MyQuery.new("connection", "get me 1").select
NewQuery.new("connection", "get me 1").select
NewQuery.new("connection", "get me 1").select
module Query
class Original
def initialize(connection, query_string, *args)
puts "Made *new* query with #{connection.inspect}, #{query_string.inspect}, #{args.inspect}"
end
def select
puts "Selecting"
end
end
module Timeouter
extend ParameterizedConcern
def select
puts "Timing out with #{with_options[:duration]}"
Timeout.timeout(with_options[:duration]) do
super
end
end
end
module Memoizer
extend ParameterizedConcern
extended do
@query_memo ||= {}
end
def new(connection, query_string, *args)
if @query_memo.key?([connection, query_string, args])
puts "Got *memoized* query for #{connection.inspect}, #{query_string.inspect}, #{args.inspect}"
end
@query_memo[[connection, query_string, args]] ||= super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment