# Keys & Key Paths

RHObjects supports key and key paths for resolving properties on an object.

# Keys

A key is defined as a string that identifies a property. A property can be:

  • a feature or variable; or
  • a property method.

A property method is a method that doesn't require parameters and does not change state.

Keys can be resolved with the valueForKey method. For example, an RHNode object has a name property, which is the name of the node. This can be retrieved with the .valueForKey() method:

String name = node.valueForKey('name')

RHNode also has a parent property method, which returns the parent node as an RHNode instance.

Frame parent = node.valueForKey('parent')

This is functionally no different than calling node.parent() directly.

# Key Paths

A key path is a series of keys separated by a period. Key paths are resolved by evaluating the keys in sequence and returning Undefined if a key in the sequence cannot be resolved. For example, the name of the parent node can be retreived with a key path:

String parentName = node.valueForKeyPath('parent.name')

This is similar to calling node.parent().name(), but is more robust since it will not crash if node.parent() cannot be resolved.

Key paths permit complex relationships to be resolved in a line of code. For example, say we have an RHNode instance and want to know the number of items in the node's owner's personal workspace. In long form:

// Get the personal workspace as an RHNode
Frame personalWorkspace = user.personalworkspace()

// Get the descendents as an RHNodeQuery
Frame descendents = personalworkspace.descendents()

// Get the count of the RHNodeQuery
Integer pwsItemCount = descendents.count()

Since all methods are properties they can be chained together into a key path and resolved as follows:

Integer pwsItemCount = user.valueForKeyPath('personalworkspace.descendents.count')

Key paths can also be used with the Assoc, List, RecArray, Record, String, and Date data types by using the $RHCore.DataUtils.valueForKeyPath() function.

For example, with a String:

String text = "  here is          a string"

String text2 = $RHCore.DataUtils.valueForKeyPath(text, 'trim.compress.capitalize')

> Here Is A String

Or, with a Date:

Date now = Date.Now()

String dayOfWeek = $RHCore.DataUtils.valueForKeyPath(now, 'dayofweek.quote')

> "Friday"

# With Templates

Keypaths can be used in RHTemplate when resolving variable and some template tags. For example:

{{ user.personalworkspace.descendents.count }}
Last Updated: 5/20/2019, 11:42:35 AM