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

Implement the JS::Object#to_b method. #247

Closed
wants to merge 1 commit into from

Conversation

ledsun
Copy link
Contributor

@ledsun ledsun commented Jul 23, 2023

A boolean value in JavaScript is always a JS::Object instance from Ruby's point of view.
Therefore, if we use the boolean value returned by a JavaScript function as the condition for an if expression in Ruby, the if expression will always be true.

if searchParams.has('phrase')
  # Always pass through here.
  ...
else
  ...
end

Think of searchParams as an instance of JavaScript's SearchParams class.
This is not the expected behavior.

Therefore, we can implement the JS::Object#to_b method to convert JavaScript boolean values to Ruby boolean values.

It is intended to be used in the following ways:

if searchParams.has('phrase').to_b
  ...
else
  ...
end

I implemented the to_b method by referring to the implementation of the to_s method.
If you prefer a different implementation, please let me know.

We can treat the return value of a JavaScript function as a condition for a Ruby if expression as follows:.
`if searchParams.has('phrase').to_b`.
@kateinoigakukun
Copy link
Member

kateinoigakukun commented Jul 23, 2023

I am a little reluctant about introducing a new conversion method that is not used in the Ruby standard library.1
As you know, we already have to_i, to_f, and to_s, so you may feel introducing to_b is a straightforward way. However, we already have JS::Object#== and we can compare a receiver object with JS.eval("return true") to satisfy the given use case. (On the other hand, other to_x has no other way to satisfy their requirement)

Therefore, I'd like to suggest defining JS::True = JS.eval("return true") and JS::False as well instead of adding a new conversion method.

Footnotes

  1. Actually to_b has been rejected in Ruby repeatedly https://bugs.ruby-lang.org/issues/6180 https://bugs.ruby-lang.org/issues/11848

@ledsun
Copy link
Contributor Author

ledsun commented Jul 23, 2023

We did not consider the point of matching the standard Ruby method definitions.
I agree with the policy to define JS::True and JS::False.

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

Successfully merging this pull request may close these issues.

2 participants