Skip to content

Commit

Permalink
* Test passing non symbol into attribute name
Browse files Browse the repository at this point in the history
  • Loading branch information
PikachuEXE committed Oct 11, 2023
1 parent e651491 commit fa465cf
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
14 changes: 12 additions & 2 deletions lib/contracted_value/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -182,10 +182,17 @@ def extract_value(hash)
attr_reader :default_value

def raise_error_if_inputs_invalid
raise_error_if_name_invalid
raise_error_if_refrigeration_mode_invalid
raise_error_if_default_value_invalid
end

def raise_error_if_name_invalid
return if name.is_a?(Symbol)

raise NotImplementedError, "Internal error: name is not a symbol (#{name.class.name})"
end

def raise_error_if_refrigeration_mode_invalid
return if RefrigerationMode::Enum.all.include?(refrigeration_mode)

Expand Down Expand Up @@ -287,16 +294,19 @@ def attribute(
refrigeration_mode: RefrigerationMode::Enum::DEEP,
default_value: Private::ATTR_DEFAULT_VALUE_ABSENT_VAL
)
# Using symbol since attribute names are limited in number
# An alternative would be using frozen string
name_in_sym = name.to_sym

attr = Attribute.new(
name: name,
name: name_in_sym,
contract: contract,
refrigeration_mode: refrigeration_mode,
default_value: default_value,
)
@attribute_set = @attribute_set.add(attr)

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

# @api private
Expand Down
16 changes: 16 additions & 0 deletions spec/contracted_value/value_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,22 @@
end
}.to raise_error(::ContractedValue::Errors::DuplicateAttributeDeclaration)
end

example "does not raise error when declaring 1 attribute with string name" do
expect {
value_class.class_eval do
attribute("attribute_1")
end
}.to_not raise_error
end

example "does not raise error when declaring 1 attribute with number name" do
expect {
value_class.class_eval do
attribute(1)
end
}.to raise_error(::NoMethodError, /undefined method `to_sym'/)
end
end


Expand Down

0 comments on commit fa465cf

Please sign in to comment.