Created
November 16, 2017 14:29
-
-
Save cblackburn-ajla/eceee892bd86750f2fe0c1c824567529 to your computer and use it in GitHub Desktop.
Watchers in ruby at the instance variable level.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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