Skip to content

Instantly share code, notes, and snippets.

@workmad3
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save workmad3/10147713 to your computer and use it in GitHub Desktop.
Save workmad3/10147713 to your computer and use it in GitHub Desktop.
class ClassToAddMethodsTo
def self.special_attr_accessor(attr, set: ->(val){val}, get: ->(val){val})
define_method attr do
get.(instance_variable_get "@#{attr}")
end
define_method "#{attr}=" do |rhs|
instance_variable_set "@#{attr}", set.(rhs)
end
end
special_attr_accessor :x, set: ->(val){val*3000}, get: ->(val){val.fdiv(300)}
def initialize(x)
self.x = x
end
end
foo = ClassToAddMethodsTo.new(1)
puts "starting x: #{foo.x}"
foo.x = 30
puts "new x: #{foo.x}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment