Skip to content

Instantly share code, notes, and snippets.

@dlt
Created June 7, 2010 14:00
Show Gist options
  • Save dlt/428690 to your computer and use it in GitHub Desktop.
Save dlt/428690 to your computer and use it in GitHub Desktop.
# Module Frequency
# A small dsl written in ruby to work with frequency events (never, sometimes, always..)
#
#
# Alteracoes:
# * removi "if block_given?" e passei &block como parametro para #execute_with_probability
# para remover duplicacao
# * mudei #correct_if_string
module Frequency
NORMALLY = 0.75
SOMETIMES = 0.50
RARELY = 0.25
# always do something
# example:
# always { puts "ok"}
def always(cond={})
yield if block_given?
end
# normally (75%) do something,
# see sometimes method
# example:
# normally { puts "ok"}
def normally(cond={}, &block)
execute_with_probability(cond, NORMALLY, &block)
end
# sometimes (50%) do something
# example:
# sometimes do
# # some code
# end
# or adjusting the probability
# sometimes :with_probability => 0.12 do
# # some code
# end
# you can use "12%" instead 0.12
# sometimes(:with_probability => '13.6%') { ... }
def sometimes(cond={}, &block)
execute_with_probability(cond, SOMETIMES, &block)
end
alias :maybe :sometimes
# rarely (25%) do something,
# see sometimes method
# example:
# rarely { puts "ok"}
def rarely(cond={}, &block)
execute_with_probability(cond, RARELY, &block)
end
# never do something
# example:
# never { puts "ok"}
def never(cond={})
end
private
def execute_with_probability(conditions,default)
rate = conditions[:with_probability] || default
rate = Float(rate) rescue correct_if_string(rate)
raise "probability must be [0..100]%" unless 0 <= rate && rate <= 1
yield if Kernel.rand < rate
end
def correct_if_string(rate)
rate.to_f / 100
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment