From: Intransition on
Wonder what other's think of this as a general purpose class method.
It comes from Sinatra, but I have been seeing it's like used in other
places too.

class Module
# Sets an option to the given value. If the value is a proc,
# the proc will be called every time the option is accessed.
def set(option, value=self, &block)
raise ArgumentError if block && value != self
value = block if block
if value.kind_of?(Proc)
metadef(option, &value)
metadef("#{option}?") { !!__send__(option) }
metadef("#{option}=") { |val| set(option, Proc.new{val}) }
elsif value == self && option.respond_to?(:to_hash)
option.to_hash.each { |k,v| set(k, v) }
elsif respond_to?("#{option}=")
__send__ "#{option}=", value
else
set option, Proc.new{value}
end
self
end
end

Example:

class X
set :x, 10
end

X.x #=> 10
X.x = 5
X.x #=> 5