Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize instance #with #57

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions lib/values.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,15 @@ def initialize(*values)
const_set :VALUE_ATTRS, fields

def self.with(hash)
unexpected_keys = hash.keys - self::VALUE_ATTRS
if unexpected_keys.any?
num_recognized_keys = self::VALUE_ATTRS.count { |field| hash.key?(field) }

if num_recognized_keys != hash.size
unexpected_keys = hash.keys - self::VALUE_ATTRS
raise ArgumentError.new("Unexpected hash keys: #{unexpected_keys}")
end

missing_keys = self::VALUE_ATTRS - hash.keys
if missing_keys.any?
if num_recognized_keys != self::VALUE_ATTRS.size
missing_keys = self::VALUE_ATTRS - hash.keys
raise ArgumentError.new("Missing hash keys: #{missing_keys} (got keys #{hash.keys})")
end

Expand Down Expand Up @@ -94,9 +96,22 @@ def pretty_print(q)
end
end

# Optimized to avoid intermediate Hash instantiations.
def with(hash = {})
return self if hash.empty?
self.class.with(to_h.merge(hash))

num_recognized_keys = self.class::VALUE_ATTRS.count { |field| hash.key?(field) }

if num_recognized_keys != hash.size
unexpected_keys = hash.keys - self.class::VALUE_ATTRS
raise ArgumentError.new("Unexpected hash keys: #{unexpected_keys}")
end

args = self.class::VALUE_ATTRS.map do |field|
hash.key?(field) ? hash[field] : send(field)
end

self.class.new(*args)
end

def to_h
Expand Down