Created
October 29, 2015 22:24
-
-
Save jgaskins/f56ceeccce8a1d2d612f to your computer and use it in GitHub Desktop.
Immutable models in Ruby
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
require 'set' | |
class Model | |
def self.attributes *attrs | |
@attributes ||= Set.new | |
attr_reader *attrs | |
@attributes += attrs | |
end | |
def initialize attributes={} | |
attributes.each do |attr, value| | |
instance_variable_set "@#{attr}", value | |
end | |
end | |
def update new_attributes={} | |
self.class.new(to_h.merge(new_attributes)) | |
end | |
def to_h | |
self.class.attributes.reduce({}) { |hash, attr| | |
hash.merge! attr => send(attr) | |
} | |
end | |
end |
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
class User < Model | |
attributes :name, :email | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment