Skip to content

Instantly share code, notes, and snippets.

@cblackburn-ajla
Created November 16, 2017 14:29
Show Gist options
  • Save cblackburn-ajla/eceee892bd86750f2fe0c1c824567529 to your computer and use it in GitHub Desktop.
Save cblackburn-ajla/eceee892bd86750f2fe0c1c824567529 to your computer and use it in GitHub Desktop.
Watchers in ruby at the instance variable level.
module Watcher
# Ensure compatibility.
def self.included( mod )
mod.extend( self )
end
# Declare a watcher. The block or lambda will be invoked with argumens of what the value was and now is, in that
# order.
def watch( sym, lambda = nil, &block )
block ||= lambda
# format variable name
var = sym.to_s
var = "@#{sym}" unless var =~ /^@/
var = var.to_sym
# declare the methods
class_eval %Q{
define_method( sym ){ instance_variable_get( var ) }
define_method("#{sym}="){|v|
block.call(
instance_variable_get( var ),
instance_variable_set( var, v )
)
}
}
sym
end
module_function :watch
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment