Skip to content

Instantly share code, notes, and snippets.

@dassio
Last active August 6, 2016 09:07
Show Gist options
  • Save dassio/c6fb75d38015807c1a7e97b9d4da8af6 to your computer and use it in GitHub Desktop.
Save dassio/c6fb75d38015807c1a7e97b9d4da8af6 to your computer and use it in GitHub Desktop.
Ruby : methods to change a class
#using extend to modify a class
#extend will add an class method we will use this class method to create instance method with 'define_method' dynamiclly
require 'test/unit'
module CheckedAttributes
def self.included(klass)
klass.extend ClassMethods # here we created an class method
end
module ClassMethods
def attr_checked(attribute,&block)
define_method "#{attribute}=" do |value|
raise 'Invalid attribute' unless block.call(value)
instance_variable_set("@#{attribute}",value)
end
define_method attribute do
instance_variable_get("@#{attribute}")
end
end
end
end
class Person
include CheckedAttributes
attr_checked :age do |v|
v >= 18
end
end
class TestCheckedAttributes < Test::Unit::TestCase
def setup
@bob = Person.new
end
def test_accepts_valid_values
@bob.age = 20
assert_equal 20,@bob.age
end
def test_refuses_invalide_values
assert_raises RuntimeError, 'Invalid attribute' do
@bob.age = 17
end
end
end
#open class override
#extend clas
#define class in class's singleton_class
#using eval
#using class_val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment