Class: Module

Inherits:
Object
  • Object
show all
Defined in:
lib/opal_patches.rb,
lib/opal_patches.rb

Overview


Encoding::* constants that Opal corelib does not register


Opal ships a handful of encodings in opal/corelib/string/encoding.rb (UTF-8, UTF-16LE,BE, UTF-32LE,BE, ASCII-8BIT, ISO-8859-1, US-ASCII). Real-world gems reference many more legacy encodings that Opal never declares. When such a constant appears at class-load time (e.g. in a constant hash literal inside rack/multipart/parser.rb), Opal raises ‘NameError: uninitialized constant Encoding::FOO` and aborts the whole require chain.

Real transcoding is out of scope for Phase 2 — Workers do not need to convert ISO-2022-JP for hello-world. We install each missing constant as an alias of an encoding Opal already ships so that the constant reference succeeds. If a gem actually calls .encode onto one of these Opal will raise a clear error at the call site, which is what we want.


Module#const_defined? / Module#const_get — qualified name support


CRuby’s ‘Module#const_defined?` and `Module#const_get` both accept “Foo::Bar::Baz” style qualified names. Opal 1.8.3.rc1 supports qualified names in `const_get` but NOT in `const_defined?`, so any call like `Object.const_defined?(’Mustermann::AST::Node::Root’)‘ returns false (or raises NameError) even when the constant exists, and Mustermann’s ‘Node` factory falls through to `nil`.

Patch: split qualified names in ‘const_defined?` and walk the chain exactly like `const_get` does.

Instance Method Summary collapse

Instance Method Details

#__homura_const_defined_simpleObject



68
# File 'lib/opal_patches.rb', line 68

alias_method :__homura_const_defined_simple, :const_defined?

#const_defined?(name, inherit = true) ⇒ Boolean

Returns:

  • (Boolean)


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/opal_patches.rb', line 70

def const_defined?(name, inherit = true)
  name_str = name.to_s
  if name_str.include?('::')
    parts = name_str.split('::')
    parts.shift if parts.first.empty?  # leading "::Foo::Bar"
    current = self
    parts.each do |part|
      return false unless current.__homura_const_defined_simple(part, inherit)
      current = current.const_get(part, inherit)
      return false unless current.is_a?(Module)
    end
    true
  else
    __homura_const_defined_simple(name, inherit)
  end
end