Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright 2017 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 #ifndef GIN_DATA_OBJECT_BUILDER_H_ | |
| 6 #define GIN_DATA_OBJECT_BUILDER_H_ | |
| 7 | |
| 8 #include <utility> | |
| 9 | |
| 10 #include "base/macros.h" | |
| 11 #include "base/strings/string_piece.h" | |
| 12 #include "gin/converter.h" | |
| 13 #include "gin/gin_export.h" | |
| 14 #include "v8/include/v8.h" | |
| 15 | |
| 16 namespace gin { | |
| 17 | |
| 18 // Constructs a JavaScript object with a series of data properties. | |
| 19 // (As with default data properties in JavaScript, these properties are | |
| 20 // configurable, writable and enumerable.) | |
| 21 // | |
| 22 // Values are automatically converted using gin::Converter, though if | |
| 23 // using a type where the conversion may fail, callers must convert ahead of | |
| 24 // time. | |
| 25 // | |
| 26 // This class avoids the pitfall of using v8::Object::Set, which may invoke | |
| 27 // setters on the object prototype. | |
| 28 // | |
| 29 // Expected usage: | |
| 30 // v8::Local<v8::Object> object = gin::DataObjectBuilder(isolate) | |
| 31 // .Set("boolean", true) | |
| 32 // .Set("integer", 42) | |
| 33 // .Finish(); | |
| 34 // | |
| 35 // Because this builder class contains local handles, callers must ensure it | |
| 36 // does not outlive the scope in which it is created. | |
| 37 class GIN_EXPORT DataObjectBuilder { | |
| 38 public: | |
| 39 explicit DataObjectBuilder(v8::Isolate* isolate); | |
| 40 | |
| 41 template <typename T> | |
| 42 DataObjectBuilder& Set(base::StringPiece key, T&& value) { | |
| 43 v8::Local<v8::String> v8_key = StringToSymbol(isolate_, key); | |
| 44 v8::Local<v8::Value> v8_value = | |
| 45 ConvertToV8(isolate_, std::forward<T>(value)); | |
| 46 CHECK(object_->CreateDataProperty(context_, v8_key, v8_value).ToChecked()); | |
| 47 return *this; | |
| 48 } | |
| 49 | |
| 50 v8::Local<v8::Object> Finish() { | |
|
Devlin
2017/04/26 18:30:24
nitty nit: most Builders seem to have a Build() ra
jbroman
2017/04/27 15:26:31
OK, done. I agree that it's more usual, though it
| |
| 51 v8::Local<v8::Object> result = object_; | |
| 52 object_.Clear(); | |
| 53 return result; | |
| 54 } | |
| 55 | |
| 56 private: | |
| 57 v8::Isolate* isolate_; | |
| 58 v8::Local<v8::Context> context_; | |
| 59 v8::Local<v8::Object> object_; | |
| 60 | |
| 61 DISALLOW_COPY_AND_ASSIGN(DataObjectBuilder); | |
| 62 }; | |
| 63 | |
| 64 } // namespace gin | |
| 65 | |
| 66 #endif // GIN_DATA_OBJECT_BUILDER_H_ | |
| OLD | NEW |