module M1
def self.included(othermod)
puts “M1 was included into #{othermod}”
end
end
module M2
def self.prepended(othermod)
puts “M2 was prepended to #{othermod}”
end
end
class C
include M1
include M2
end
# 输出
M1 was included into C
M2 was prepended to C
module M
def self.method_added(method)
puts “New method: M##{method}”
end
def my_method; end
end
# 输出
New method: M#my_method
def add_checked_attribute(klass, attribute)
eval "
class #{klass}
def #{attribute}=(value)
raise 'Invalid attribute' unless value
@#{attribute} = value
end
def #{attribute}()
@#{attribute}
end
end
"
end
add_checked_attribute(String, :my_attr)
t = "hello,kitty"
t.my_attr = 100
puts t.my_attr
t.my_attr = false
puts t.my_attr
def add_checked_attribute(klass, attribute)
klass.class_eval do
define_method "#{attribute}=" do |value|
raise "Invaild attribute" unless value
instance_variable_set("@#{attribute}", value)
end
define_method attribute do
instance_variable_get "@#{attribute}"
end
end
end
class Class
def attr_checked(attribute, &validation)
define_method "#{attribute}=" do |value|
raise "Invaild attribute" unless validation.call(value)
instance_variable_set("@#{attribute}", value)
end
define_method attribute do
instance_variable_get "@#{attribute}"
end
end
end
String.add_checked(:my_attr){|v| v >= 180 }
t = "hello,kitty"
t.my_attr = 100 #Invaild attribute (RuntimeError)
puts t.my_attr
t.my_attr = 200
puts t.my_attr #200
module CheckedAttributes
def self.included(base)
base.extend ClassMethods
end
end
module ClassMethods
def attr_checked(attribute, &validation)
define_method "#{attribute}=" do |value|
raise "Invaild attribute" unless validation.call(value)
instance_variable_set("@#{attribute}", value)
end
define_method attribute do
instance_variable_get "@#{attribute}"
end
end
end
class Person
include CheckedAttributes
attr_checked :age do |v|
v >= 18
end
end