Skip to content

Instantly share code, notes, and snippets.

@plainprogrammer
Created November 22, 2014 22:59
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 plainprogrammer/66d7df7c8bcd4e91c727 to your computer and use it in GitHub Desktop.
Save plainprogrammer/66d7df7c8bcd4e91c727 to your computer and use it in GitHub Desktop.
Renewable Objects (Immutability by Default) — A more Functional way to do OOP
class Person
include Renewable
attr_accessor :name, :age
def celebrate_birthday
self.renew(age: age + 1)
end
end
john = Person.new(name: 'John', age: 24)
john.name # 'John'
john.name = 'Brandon' # NoMethodError
jack = john.renew(name: 'Jack')
new_john = john.celebrate_birthday
module Renewable
def initialize(attributes = {})
# Iterates through provided attributes and sets the
# instance variables before freezing the object.
end
def renew(attributes = {})
# Duplicates self and updates the provided attributes,
# freezes the new instance and returns it.
end
module ClassMethods
def attr_accessor
# Sets up standard getter
# Bypasses creation of a setter
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment