object.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. module V8
  2. class Object
  3. include Enumerable
  4. def initialize(native, portal)
  5. @native, @portal = native, portal
  6. end
  7. def [](key)
  8. @portal.open do |to|
  9. to.rb(@native.Get(to.v8(key)))
  10. end
  11. end
  12. def []=(key, value)
  13. value.tap do
  14. @portal.open do |to|
  15. @native.Set(to.v8(key), to.v8(value))
  16. end
  17. end
  18. end
  19. def to_s
  20. @portal.open do |to|
  21. to.rb(@native.ToString())
  22. end
  23. end
  24. def each
  25. @portal.open do |to|
  26. for prop in to.rb(@native.GetPropertyNames())
  27. yield prop, self[prop]
  28. end
  29. end
  30. end
  31. def respond_to?(method)
  32. super or self[method] != nil
  33. end
  34. def method_missing(name, *args, &block)
  35. if name.to_s =~ /(.*)=$/
  36. if args.length > 1
  37. self[$1] = args
  38. return args
  39. else
  40. self[$1] = args.first
  41. return args
  42. end
  43. end
  44. return super(name, *args, &block) unless self.respond_to?(name)
  45. property = self[name]
  46. if property.kind_of?(V8::Function)
  47. property.methodcall(self, *args)
  48. elsif args.empty?
  49. property
  50. else
  51. raise ArgumentError, "wrong number of arguments (#{args.length} for 0)" unless args.empty?
  52. end
  53. end
  54. end
  55. end
  56. class Object
  57. def eval_js(javascript)
  58. V8::Context.new(:with => self).eval(javascript)
  59. end
  60. end