Skip to content

Instantly share code, notes, and snippets.

@rsslldnphy
Created October 17, 2013 11:48
Show Gist options
  • Save rsslldnphy/7023500 to your computer and use it in GitHub Desktop.
Save rsslldnphy/7023500 to your computer and use it in GitHub Desktop.
Looong methods! And code in the initializer!
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
@gavinlaking
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment