Created
July 10, 2015 22:46
-
-
Save norbajunior/992d8fb68cd561a0fcfe to your computer and use it in GitHub Desktop.
This file contains 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
class Object | |
def self.attributes(*attrs) | |
attrs.each do |attr| | |
define_method attr do | |
instance_variable_get "@#{attr}" | |
end | |
define_method "#{attr}=" do |value| | |
instance_variable_set "@#{attr}", value | |
end | |
end | |
end | |
end | |
Object.instance_eval do | |
def setters(*attrs) | |
attrs.each do |attr| | |
class_eval <<-EOS | |
def #{attr}=(value) | |
@#{attr} = value | |
end | |
EOS | |
end | |
end | |
def getters(*attrs) | |
attrs.each do |attr| | |
class_eval "def #{attr} ; @#{attr} ; end" | |
end | |
end | |
end | |
class Person | |
attributes :age, :town | |
setters :height | |
getters :name | |
end | |
Person.class_eval do | |
def initialize(name:) | |
@name = name | |
end | |
end | |
person = Person.new name: 'Norberto' | |
person.age = 28 | |
person.town = 'Porto' | |
person.height = 1.70 | |
puts person.name # Norberto | |
puts person.age # 28 | |
puts person.town # Porto |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment