Skip to content

Commit

Permalink
Fix bug in truthy/falsy tests for booleans as objects
Browse files Browse the repository at this point in the history
  • Loading branch information
adambeynon committed Dec 6, 2013
1 parent 71c0f56 commit 1afbc44
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -27,6 +27,10 @@
`!` as a def method name, and implements the method on `BasicObject`,
`NilClass` and `Boolean`.

* Fixed bug where true/false as object literals from javascript were not
correctly being detected as truthy/falsy respectively. This is due to the
javascript "feature" where `new Boolean(false) !== false`.

* Moved `native.rb` to stdlib. Native support must now be explicitly required
into Opal. `Native` is also now a module, instead of a top level class.
Also added `Native::Object#respond_to?`.
Expand Down
4 changes: 2 additions & 2 deletions lib/opal/nodes/helpers.rb
Expand Up @@ -67,7 +67,7 @@ def js_truthy(sexp)
end

with_temp do |tmp|
[fragment("(#{tmp} = "), expr(sexp), fragment(") !== false && #{tmp} !== nil")]
[fragment("((#{tmp} = "), expr(sexp), fragment(") !== nil && (!#{tmp}._isBoolean || #{tmp} == true))")]
end
end

Expand All @@ -81,7 +81,7 @@ def js_falsy(sexp)
end

with_temp do |tmp|
[fragment("(#{tmp} = "), expr(sexp), fragment(") === false || #{tmp} === nil")]
[fragment("((#{tmp} = "), expr(sexp), fragment(") === nil || (#{tmp}._isBoolean && #{tmp} == false))")]
end
end

Expand Down
23 changes: 23 additions & 0 deletions spec/opal/core/runtime/truthy_spec.rb
@@ -0,0 +1,23 @@
class Boolean
def self_as_an_object
self
end
end

describe "Opal truthyness" do
it "should evaluate to true using js `true` as an object" do
if true.self_as_an_object
called = true
end

called.should be_true
end

it "should evaluate to false using js `false` as an object" do
if false.self_as_an_object
called = true
end

called.should be_nil
end
end

0 comments on commit 1afbc44

Please sign in to comment.