Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created October 29, 2015 22:24
Show Gist options
  • Save jgaskins/f56ceeccce8a1d2d612f to your computer and use it in GitHub Desktop.
Save jgaskins/f56ceeccce8a1d2d612f to your computer and use it in GitHub Desktop.
Immutable models in Ruby
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
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