Method: Twig::Extension::Core.constant

Defined in:
lib/twig/extension/core.rb

.constant(constant, object = nil, defined_test: false) ⇒ Object

Parameters:

  • constant (String)
  • object (Object, nil) (defaults to: nil)
  • defined_test (Boolean) (defaults to: false)


327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/twig/extension/core.rb', line 327

def self.constant(constant, object = nil, defined_test: false)
  unless object.nil?
    if defined_test
      return object.class.const_defined?(constant)
    end

    return object.class.const_get(constant)
  end

  if constant.include?('::')
    class_name, _, constant = constant.rpartition('::')
  else
    class_name = Kernel.name
  end

  unless Object.const_defined?(class_name)
    return false if defined_test

    raise Error::Runtime, "Class #{class_name} does not exist."
  end

  klass = Object.const_get(class_name)

  unless klass.const_defined?(constant)
    return false if defined_test

    raise Error::Runtime, "Class #{class_name} does not have a constant #{constant}."
  end

  return true if defined_test

  klass.const_get(constant)
end