Monday, May 3, 2010

Dynamic finder with #doesNotUnderstand, #perform and Regex

This is the sequel to SandstoneDb, simple ActiveRecord style persistence screencast.

I show how to:
  • override Object#doesNotUnderstand in your class to answer to unknown messages
  • use regular expressions to extract substrings
  • use #perform: and #perform:with: to send a message dynamically
  • develop new code in the debugger without stopping current call.

To learn about Regex in Pharo, read the (draft) chapter for Pharo By Example 2.

Download screencast (800x600): .mpeg 23.1 MB, .mov 37.2 MB



Here's the final code of Person#doesNotUnderstand:
doesNotUnderstand: aMessage
  "aMessage arguments  #('Laurent' 10)"
  "aMessage selector #findAllByName:Age:"
 
  | selRegex findSelector searchSelectors searchedValues |
  selRegex := 'find(All|First)By(\w+\:)+' asRegex.
  (selRegex search: aMessage selector)
      ifFalse: [^ super doesNotUnderstand: aMessage].
  
  findSelector := ((selRegex subexpression: 2) = 'All') 
                                       ifTrue: [#findAll:] 
                                       ifFalse: [#find:].
        
  searchSelectors := (selRegex subexpressions: 3) collect: 
                       [:aSymbol|
                        aSymbol asLowercase allButLast asSymbol].
        
  (self allSelectors includesAllOf: searchSelectors) 
                 ifFalse: [^ super doesNotUnderstand: aMessage].
        
  searchedValues := aMessage arguments.
 
  ^ self 
    perform: findSelector 
    with: [:aPerson| |values| 
           values := searchSelectors collect: 
                      [:aSelector| 
                       aPerson perform: aSelector].
           searchedValues = values].

1 comment:

  1. The modern Rolex GMT-Master II was introduced in 2005 in the replica watches form of the all-gold GMT-Master II Ref. 116718LN. It was to be an anniversary model, and so came with a green dial in Rolex's replica watches signature hue. This new Rolex GMT-Master II's diameter was unchanged at 40mm, but it rolex replica possessed what is now sometimes known as the "Super Case" and "Maxi Dial", Rolex-speak for larger case and dial with fatter markers, respectively, and so it looks and wears larger than its 40mm size would suggest. And replica watches uk for the first time, it came with a ceramic bezel that Rolex claims to be virtually scratch and fade-proof. Other changes include a larger Trip-lock crown, a new bracelet with polished center links and Easylink extension, green 24-hour hand, and a new replica watches sale movement, the calibre 3186. The new 3186 movement has no new functions rolex replica over the older calibre 3185, but it is equipped with Rolex's new Parachrom hairspring and rolex replica the operation of the jumping hour hand is now smoother and replica watches more precise.

    ReplyDelete