Skip to content

Instantly share code, notes, and snippets.

@norbajunior
Created July 10, 2015 22:46
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 norbajunior/992d8fb68cd561a0fcfe to your computer and use it in GitHub Desktop.
Save norbajunior/992d8fb68cd561a0fcfe to your computer and use it in GitHub Desktop.
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