In a previous post we learned about the get and getAll methods to get objects from the registry. Ratpack also provides the first method to get objects from the registry. This method accepts a Function that is applied to the elements of a given type. The first element where the Function returns a non null value is returned encapsulated in an Optional object. If the Function returns a null value for all elements than Optional.empty() is returned.

package com.mrhaki.ratpack

import ratpack.registry.Registry
import ratpack.registry.RegistrySpec
import spock.lang.Specification

class FindFirstRegistrySpec extends Specification {

    Registry registry

    def setup() {
        // Setup registry with two objects of type User.
        registry = Registry.of { RegistrySpec registrySpec ->
            registrySpec.add(new User(username: 'mrhaki'))
            registrySpec.add('hubert')
            registrySpec.add(new User(username: 'hubert'))
            registrySpec.add('mrhaki')
        }
    }

    def "find User where username starts with mr"() {
        when:
        // First element that returns a non null value
        // is return encapsulated in an Optional.
        final Optional user = registry.first(User) { user ->
            // If username property starts with
            // "mr" than return user as non null value.
            user.username.startsWith("mr") ? user : null
        }

        then:
        user.get().username == 'mrhaki'
    }
} 

Written with Ratpack 1.1.1.

Original blog post

shadow-left