Skip to content

Commit

Permalink
Merge 883f54a into 8095a18
Browse files Browse the repository at this point in the history
  • Loading branch information
notEthan committed Sep 9, 2021
2 parents 8095a18 + 883f54a commit 48a9cd8
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/jsi/schema_classes.rb
Expand Up @@ -130,7 +130,21 @@ def accessor_module_for_schema(schema, conflicting_modules: , setters: true)
conflicting_instance_methods = (conflicting_modules + [m]).map do |mod|
mod.instance_methods + mod.private_instance_methods
end.inject(Set.new, &:|)
accessors_to_define = schema.described_object_property_names.map(&:to_s) - conflicting_instance_methods.map(&:to_s)

accessors_to_define = schema.described_object_property_names.select do |name|
do_define = true
# must be a string
do_define &&= name.respond_to?(:to_str)
# must not begin with a digit
do_define &&= name !~ /\A[0-9]/
# must not contain characters special to ruby syntax
do_define &&= name !~ /[\\\s\#;\.,\(\)\[\]\{\}'"`%\+\-\/\*\^\|&=<>\?:!@\$~]/
# must not conflict with any method on a conflicting module
do_define &&= !conflicting_instance_methods.any? { |m| m.to_s == name }

do_define
end

accessors_to_define.each do |property_name|
define_method(property_name) do |*a|
self[property_name, *a]
Expand Down
42 changes: 42 additions & 0 deletions test/base_test.rb
Expand Up @@ -512,6 +512,48 @@
assert_equal(Set[schema], subject.jsi_schemas)
end
end
describe 'properties with names to ignore' do
class X
def to_s
'x'
end
end
let(:schema_content) do
{
'type' => 'object',
'properties' => {
X.new => {}, # not a string
'[]' => {}, # operator, also conflicts with Base
'-@' => {}, # unary operator
'~' => {}, # unary operator
'%' => {}, # binary operator
'0' => {}, # digit
1 => {}, # digit, not a string
},
}
end
let(:instance) do
{
X.new => 'x',
'[]' => '[]',
'-@' => '-@',
'~' => '~',
'%' => '%',
'0' => '0',
1 => 1,
}
end
it 'does not define readers' do
assert_raises(NoMethodError) { subject.x }
assert_equal(nil, subject['test']) # #[] would SystemStackError since reader calls #[]
assert_equal(JSI::Base, subject.method(:[]).owner)
assert_raises(NoMethodError) { -subject }
assert_raises(NoMethodError) { ~subject }
assert_raises(NoMethodError) { subject % 0 }
assert_raises(NoMethodError) { subject.send('0') }
assert_raises(NoMethodError) { subject.send('1') }
end
end
end
describe 'writers' do
it 'writes attributes described as properties' do
Expand Down

0 comments on commit 48a9cd8

Please sign in to comment.