Module#set

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs