# Module#set

**URL:** <https://www.ruby-forum.com/t/module-set/183865>\
**Category:** Ruby\
**Created:** [February 22, 2010, 2:55am UTC](https://www.ruby-forum.com/t/module-set/183865 "2010-02-22T02:55:39Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tcsnide](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/eb8c5e/32.png) [@tcsnide](https://www.ruby-forum.com/u/tcsnide)\
**Post date:** [February 22, 2010, 2:55am UTC](https://www.ruby-forum.com/t/module-set/183865/1 "2010-02-22T02:55:39Z")

</div>

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
