Last active
August 29, 2015 14:01
-
-
Save oinak/e3ed2e79004ed139c4c6 to your computer and use it in GitHub Desktop.
segundo ejercicio del taller de metaprogramacón
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 Atribulator | |
module ClassMethods | |
def my_attr_reader(name) | |
define_method("#{name}") do | |
instance_variable_get("@#{name}") | |
end | |
end | |
def my_attr_writer(name, my_type = nil) | |
if my_type.nil? | |
define_method("#{name}=") do |value| | |
instance_variable_set("@#{name}", value) | |
end | |
else | |
define_method("#{name}=") do |value| | |
raise ArgumentError unless value.is_a?(my_type) | |
instance_variable_set("@#{name}", value) | |
end | |
end | |
end | |
def my_attr_accessor(name, forced_type = nil) | |
my_attr_reader(name) | |
my_attr_writer(name, forced_type) | |
end | |
end | |
def self.included(klass) | |
klass.extend ClassMethods | |
end | |
end | |
class Two | |
include Atribulator | |
my_attr_accessor :foo, String | |
end | |
two = Two.new | |
two.foo = "bar" | |
puts "two.foo => #{two.foo}" | |
begin | |
two.foo = 2 | |
rescue | |
puts "cazado!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment