Created
November 22, 2014 22:59
-
-
Save plainprogrammer/66d7df7c8bcd4e91c727 to your computer and use it in GitHub Desktop.
Renewable Objects (Immutability by Default) — A more Functional way to do OOP
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 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 |
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
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