Created
October 17, 2013 11:48
-
-
Save rsslldnphy/7023500 to your computer and use it in GitHub Desktop.
Looong methods! And code in the initializer!
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
module Id::Model | |
def initialize(data = {}) | |
@data = data.reduce({}) do |acc, (k, v)| | |
field = fields[k.to_sym] | |
v ||= field.default! | |
v = field.type.new(v) if field.type.is_a?(Id::Model) && !v.nil? | |
acc.merge(k.to_s => Id::Hashifier.enhash(v)) | |
end | |
end | |
def set(update) | |
updated = data.merge(update.stringify_keys) | |
self.class.new(updated) | |
end | |
def unset(*fields) | |
fields = fields.map(&:to_s) | |
updated = data.except(*fields) | |
self.class.new(updated) | |
end | |
def eql? other | |
other.is_a?(Id::Model) && other.data.eql?(self.data) | |
end | |
alias_method :==, :eql? | |
def hash | |
data.hash | |
end | |
attr_reader :data | |
alias_method :to_hash, :data | |
def self.included(base) | |
base.send :extend, Id::Field, Id::Association, Id::EtaExpansion | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the initializer is doing too much. Indoctrinated as I am, dogmatic as I may sound! Id::Hashifier looks like a good candidate (only by name obviously) for this functionality.
Also, mutation on line 18- tsk tsk.