Skip to content

Commit

Permalink
* Make code "Object Shape friendly"
Browse files Browse the repository at this point in the history
  • Loading branch information
PikachuEXE committed Oct 8, 2023
1 parent 24a26f3 commit e651491
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
13 changes: 6 additions & 7 deletions lib/contracted_value/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,8 @@ def initialize(input_attr_values = {})
)
end

@attr_values = {}

self.class.send(:attribute_set).each_attribute do |attribute|
attr_value = attribute.extract_value(input_attr_values_hash)

Expand All @@ -253,8 +255,8 @@ def initialize(input_attr_values = {})

# Using symbol since attribute names are limited in number
# An alternative would be using frozen string
instance_variable_set(
:"@#{attribute.name}",
@attr_values.store(
attribute.name.to_sym,
sometimes_frozen_attr_value,
)
end
Expand All @@ -265,10 +267,7 @@ def initialize(input_attr_values = {})
# rubocop:enable Metrics/CyclomaticComplexity

def to_h
self.class.send(:attribute_set).
each_attribute.each_with_object({}) do |attribute, hash|
hash[attribute.name] = instance_variable_get(:"@#{attribute.name}")
end
@attr_values.clone
end

# == Class interface == #
Expand Down Expand Up @@ -297,7 +296,7 @@ def attribute(
)
@attribute_set = @attribute_set.add(attr)

attr_reader(name)
define_method(name) { @attr_values[name.to_sym] }
end

# @api private
Expand Down
8 changes: 7 additions & 1 deletion spec/contracted_value/value_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,19 @@

it "does not raise error when input is a value" do
aggregate_failures do
new_val = nil
expect {
value_class.new(
new_val = value_class.new(
value_class.new(
default_inputs,
),
)
}.to_not raise_error
if new_val
default_inputs.each_pair do |attr_name, attr_val|
expect(new_val.public_send(attr_name)).to eq(attr_val)
end
end
end
end

Expand Down

0 comments on commit e651491

Please sign in to comment.