Module: Cattri::Introspection::ClassMethods

Defined in:
lib/cattri/introspection.rb

Overview

Class-level introspection methods exposed via ‘.attribute_defined?`, `.attribute`, etc.

Instance Method Summary collapse

Instance Method Details

#attribute(name) ⇒ Cattri::Attribute?

Returns the attribute definition for the given name.

Includes inherited definitions if available.

Parameters:

  • name (Symbol, String)

    the attribute name

Returns:



37
38
39
# File 'lib/cattri/introspection.rb', line 37

def attribute(name)
  attribute_registry.defined_attributes(with_ancestors: true)[name.to_sym] # steep:ignore
end

#attribute_defined?(name) ⇒ Boolean

Returns true if the given attribute has been defined on this class or any ancestor.

Parameters:

  • name (Symbol, String)

    the attribute name

Returns:

  • (Boolean)


27
28
29
# File 'lib/cattri/introspection.rb', line 27

def attribute_defined?(name)
  !!attribute(name)
end

#attribute_definitions(with_ancestors: false) ⇒ Hash{Symbol => Cattri::Attribute}

Returns a hash of attribute definitions defined on this class.

Includes inherited attributes if ‘with_ancestors` is true.

Parameters:

  • with_ancestors (Boolean) (defaults to: false)

Returns:



57
58
59
# File 'lib/cattri/introspection.rb', line 57

def attribute_definitions(with_ancestors: false)
  attribute_registry.defined_attributes(with_ancestors: with_ancestors) # steep:ignore
end

#attribute_methodsHash{Symbol => Set<Symbol>}

Returns a hash of all methods defined by Cattri attributes.

This includes accessors, writers, and predicates where applicable.

Returns:

  • (Hash{Symbol => Set<Symbol>})


66
67
68
69
70
# File 'lib/cattri/introspection.rb', line 66

def attribute_methods
  attribute_registry.defined_attributes(with_ancestors: true).transform_values do |attribute| # steep:ignore
    Set.new(attribute.allowed_methods)
  end
end

#attribute_source(name) ⇒ Module?

Returns the original class or module where the given attribute was defined.

Parameters:

  • name (Symbol, String)

    the attribute name

Returns:

  • (Module, nil)


76
77
78
# File 'lib/cattri/introspection.rb', line 76

def attribute_source(name)
  attribute(name)&.defined_in
end

#attributes(with_ancestors: false) ⇒ Array<Symbol>

Returns a list of attribute names defined on this class.

Includes inherited attributes if ‘with_ancestors` is true.

Parameters:

  • with_ancestors (Boolean) (defaults to: false)

Returns:

  • (Array<Symbol>)


47
48
49
# File 'lib/cattri/introspection.rb', line 47

def attributes(with_ancestors: false)
  attribute_registry.defined_attributes(with_ancestors: with_ancestors).keys # steep:ignore
end