Thursday, 2 July 2009

another LIFT rant...


Yesterday I got so frustrated with Liftweb and it's lack of documentation that I decided to pick up apache wicket. Now I had picked up wicket almost a year ago and despite all it's cool features I decided against pursueing it any further. Well guess what those same reasons popped up again yesterday. Needless to say I'm back with lift. I've seen a lot of complaints about lift's documentation and all that but I'm not convinced that the reason I'm still with lift is the self same reason I wont pick up wicket anytime soon. Enough ranting.
So I figure what's the point of joining the rants when I could spend my time better contributing in my own small way to solving the problem? So I decided to write a little tutorial (seriously this is nothing serious) about lift.

Some foundations...

Lift is written in scala (so if you dont know scala you might as well stop reading now). It is said to have picked up the nice things from all the other frameworks and of course since scala is said to scale well, it is expected that lift scales well (dont take my word for it). In anycase... enough cliches and truism... here's how I understand lift.

In lift there are basically 3 parts to your web app

1. The view - your normal (well formed) xhtml document. The special thing though is that there are all these special tags that correspond to class methods that you arbitrarily create.
2. The boot system - this is a class where all the configuration of your webapp is stored. For instance you'd store the package where you have the tag classes I mentioned above here.
3. Your special tags - ok, seriously, this can get really confusing but humour me for just a moment.

So how does this all come together? Well, the special tags I mentioned above are actually called 'snippets' - and yes they are much more than special tags. They are more like mini-controllers that have been thrown into your html file. So when lift is processing a request for an html view and it encounters any one of these special tags (snippets), the class method corresponding to the special tag's name is called. This class method is free to roam the wild and do what ever it likes (after all I just said it's a mini controller). But it's not all about the snippets.... the view (html files) that I talked about also have this cool feature called templating. What happens in essense is that you can have a template html file (one or more) that defines the common functionality. Then you can have other xhtml fragments in other files that then define only the part of your website that changes. No, I'm not exactly talking inheritance here but then again I'm not sure what I'm talking about ;)

pre implementation
Ok so let's see an implementation to get some concrete understanding of all the nonsense I've just said... I'll basically keep it really simple...

We'll have one web page (actually a template and 2 snippets)
One class with two methods

The website will basically give potential spellings of english words in yoruba. On that note some of the other things I'll touch on are session variables, request variables and .... that's it!
I just have to say one more thing... lift relies a lot on maven so if you hate maven... why would you hate someone that's never done anything to harm you?

view implementation

Remember the template we talked about earlier? well this is how it works. You have a standard xhtml file that contains how you want your site to look. Inside that file you can place <lift:bind name="content" /> tags at any position where you think the content should change dynamically. You then define other xhtml files that would define dynamic content. These other xhtml files will specify what template LIFT should use by using the <lift:surround with="default" at="content"></lift:surround> tag. These xhtml files would also contain special tags that map to class methods that you define. For instance <lift:yoruba.spell form="GET">, in the example below, tells lift that it should load and call the spell method from the "Yoruba" class defined in the snippet package.


<lift:surround with="default" at="content">

  <h2>Welcome to your project!</h2>
  <p>
    <lift:yoruba.spell form="GET">
      word: <yo:word /><br/>
      <yo:submit />
      <yo:spellings />
    </lift:yoruba.spell>
  </p>
</lift:surround>



snippet implementation

The snippet is a plain old scala class (POSC just doesn't do it as an acronym now does it?). In any case, this method should contain a method called spell (because in your html file you refered to a method called "spell" within the "Yoruba" class. This method should call a special method called bind where you define the default values of xhtml fields and how the corresponding class variables are populated when a request comes in. Ideally you should have a variable that corresponds to each <yo:submit /> tag within the <lift:yoruba.spell form="GET"> tag. The first parameter of the bind method is "yo". The 2nd should be pretty obvious. The third though, simply says where ever the <yo:word /> tag is encountered the default value is yoruba.word and the field that should populated when a request gets to the server is defined by the method "word = _" (if you dont understand this construct google "scala partial functions" as my fingers are beginning to ache!).

One note worthy thing is that the other of parameters in the bind method is important (or so I think). So for instance if I had put the submit binding definition after the spelling one then potentially the calculated spelling would only make it to the client on the next response not the current one. **I think this is something I should verify but then again there's a reason for the disclaimer at the top of this blog**

Another thing to note is that since each request comes on it's own and may (would) trigger another instance of your snippet class if you set the value of a field when the request comes in it may see that value set when the response gets back to the client. Ways around this include using RequestVar/SessionVar as I've done here or using S.mapSnippet("yoruba.spell", a local method defined within Yoruba.spell) to change the binding on the snippet. The result of the later makes smart use of scala's perspective on scope and the fact that scala accepts higher level methods. Actually you'll see this later method used here. I opted to go with the SessionVar/RequestVar approach because I want previous spellings to show up on the screen as long as the session hasn't timed out. To use these SessionVar, you create an object that extends SessionVar along with a default constructor. The use of RequestVar is a little different but it's explained in the LIFT Book (it may be a good idea for you at this time to google "liftbook master.pdf" if you've not already done so).


package eni.ola.snippet


import scala.xml.{ NodeSeq, Text }

import net.liftweb._
import http._
import SHtml._
import S._

import util._
import Helpers._

class Yoruba {
  object spellings extends SessionVar[NodeSeq](Text(""))
  var word = ""
  
  def spell(xhtml:NodeSeq):NodeSeq = {
    def process():Unit = {
      val x = koole(word.toString, null)
      
      spellings(
        <div>{ x }</div>
        <hr/>
        <span>{ spellings.is }</span>
      )
    }
    
    def yoBind(xhtml:NodeSeq):NodeSeq =
        bind("yo", xhtml,
                "word" -> SHtml.text(word, word = _),

                "submit" -> SHtml.submit("epeller", process),
                "spellings" -> spellings.is
        )
    

    yoBind(xhtml)
  }

  
  val afabeti = Set("a", "\u00E1", "\u00E0") ::
                        Set("e", "\u00e8", "\u00e9", "e\u0329", "\u00E8\u0329", "\u00E9\u0329") ::
                        Set("i", "\u00EC", "\u00ED") ::
                        Set("o", "\u00F2", "\u00F3", "o\u0329", "\u00F2\u0329", "\u00F3\u0329") ::
                        Set("u", "\u00F9", "\u00Fa") ::
                        Set("s", "s\u0329") :: Nil  
  def koole(word:String, combos:List[String]):String = {
    if(word.trim == "")
      combos.reduceLeft(_+", "+_)
    else if(combos == null || combos.isEmpty)
      koole(word, List(""))
    else{
      //get list of possible letters for current letter
      val letter = word(0).toString     
      val /span>choice = { Set(letter) :: afabeti.filter(_.contains(letter)) }.reduceLeft(_ ++ _).toList


      //append the list to each existing combo
      koole(word.substring(1), choice.flatMap(x => combos.map(_+x).toList))     

    }

  }
}



en fin

So what I've done here is pretty basic. I've not touched the boot class at all as I simply just tweaked/created 2 files. The learning curve of LIFT may be steep but it sure is concise. The error messages dont help that much either but you can't win them all now can you? I assumed that you already know how to create a LIFT project using maven. If you dont here's what you do...

Install eclipse (I'm sorry Netbeans fans but I can't bring myself to work in an ugly IDE) from eclipse.org.
Install the scala eclipse plugin and m2eclipse plugin (for maven) - if you dont know where to get these from then google or bing (bing sounds so perverse).
Once you have all these set up, create a maven project. When it's time to select archetype choose "lift-archetype-basic" and voila!
To run/demo the project, you can set up a maven run configuration for your project and make the goal "jetty:run".

koole - is the Yoruba word for write it down
afabeti - is my own yoruba transliteration for the english word alphabet

Phew! I definitely won't come back to this blog for another 2 months or so... quantum mechanics beckons :(
But never say never... after all the EPL season starts this month for us Gooners (someone has to talk some sense to those ArsenalAmerica.com guys - I'm not sure they know how much changes to their site may affect my sanity). Aight... happy 4th of July

Saturday, 11 April 2009

Salvation: 3 Steps (a functional programming look at salvation)


This is by no means a definitive write-up on Salvation. In stead, it's me spending part of the Sabbath thinking about something that's as important to me as life and death. In Matthew 16:24, there's a simple three step program for salvation. The steps are

1. Deny yourself
2. Take up your cross
3. Follow me

It's easy to think of these steps as been sequential but a closer look may tell us otherwise. In fact it may also be understood that these steps are somewhat interwoven. Denying one's self is actually a fundamental and integral part of taking up your cross and following Jesus involves taking up your cross, daily (Luke includes that word in this rendation of this 3 step program). I'd like to understand this thingy more and clarify the questions. These questions include, among many others

- Is it really this easy to get salvation (what does each step entail)
- What ever happened to righteousness by grace through faith
- Is this 3 step program sequential or simultaneous


def deny(self:HumanBeing):EmptyBeing = self.recant()


freedictionary.com defines self-denial gives 2 definitions of self-denial - "Sacrifice of one's own desires or interests." and "the repression or sacrifice of one's own desires". So another question to ask is is was Jesus talking about this. If this is what he had in mind then we have to ask ourselves what if anything is the product of self denial? The simplistic answer would be losing out on some fun or better still losing out on what we truly crave. However the next question quickly springs to mind - at what cost? Interestingly, Jesus also says "we ought to count the cost" of following him. Since the question of cost will come up in every one of this 3 step program I'll leave the question of cost to either another blog or another section of this blog (I've got about 2 hours left this Sabbath after all)

An alternate explanation of "deny yourself" is to find similar phrase or scenario used by Jesus in the bible. Jesus once told Peter that he [Peter] would "deny him [Jesus]" thrice. Now this may sound like a rather ridiculous example of similar phrasology (dont think this word exists) but humor me anyway. So how does Peter deny Jesus? He very well renounces all relations and knowledge of Jesus and goes to the very extreme of cursing and swelling. He must have sounded a little like Tupac in Hit 'Em Up with quite a few 'F' words. It brings to mind how Nero and then the large christain church in the Dark Ages would require you to recant or die. So if this was what Jesus had in mind then Jesus was talking about more than just self denial (i.e. sacrificing or repressing one's own desire). He was talking about recanting on all that you believe in or would personally, individually, stand for. He's saying use sanctified 4 letter words to describe yourself (and mean it too) every moment of your life. Ok so it's looking like I'm making a meal of a man's little white lie in attempting to save his life but dont they say "Life and death is in the power of the tongue" and "out of the fullness of the heart the mouth speaketh"? Peter may have just been trying to save his life no more desperately than we should be too but in that moment he most definately meant every word of what he said enough for him to feel deep sorrow when he realized what he had just done. Interestingly I think self-denial (as seen in the first definition) is natural product of this second explanation. Or put another way deny yourself results inevitably in complete and utter self-denial.

So where the self-denial says "no thank you" when you are offered pork - it's unclean after all (if you are Jewish, Muslim or a christian that shares that believe) - Peter's example of Denial not only simple says "no thank you" but it says I never had it before, I dont know how it tastes and I sure as hell dont want anything to do with it. It's kind of like a violent attempt to rip out the very essence of you from you that's what it is (the kingdom of God suffereth violence anyone?). Denying yourself should be an act much like Daniel and his friends proposing in their hearts not be defy themselves with ....
So whereas the self-denial looks the harder and the second attempt looks extremely easier yet more far reaching. I think we'll have to talk about why it's extremely easier real soon.


def takeUpCross(being:EmptyBeing):DeadBeing = being.die()


That the cross, that must popular christian symbol of death (yes that's what I really symbolizes), has become a fashion statement is interesting. In fact as I type this I'm thinking to myself that I really should go get me a cross pendant. Seriously, though, for the Jew and in Jesus' time the cross was a symbol of more than Roman oppression - it was a symbol humilation and death. To understand this you've got to be an African (or at least from a non-western culture). Many african cultures have tightly interwoven extended family structures and if something as disgraceful such as been caught stealing happened to you were usually stuck with the stigma for the rest of your life. Now that I think of it, it's rather easy to explain in Western culture (or more specifically American culture since I've only been to Africa and US). Been seen with a cross is kind of like that stain on your record as a medical practitioner that prevents you from practicing as a doctor many years after that mark found it's way to into your record. The cross was not a palatable thing for the jew - it was simply put a death sentence - and no one wants to die (why do you think I bother reading this stuff).

The cross is such a terrible thing that it takes been utterly empty of self for you (denying yourself) to be willing and able to carry it. And to be able to continually carry the cross you've got to continually deny yourself. The cross is you signing or better still accepting your death warrant. Dietrich Bonhoeffer puts it like this "When Christ calls a man, he bids him come and die." Like Dietrich goes on to explain, this isn't physical death but more importantly it's death to all that you ever would have been had you not denied your self. The cross is only possible as a consequence of denying yourself. Both are tightly coupled (no pun intended) and inseperable. In functional programming, you'll probably want to pass the deny() function as a parameter to the takeUpCross() function so that the takeUpCross() function can call it with impunity within itself.


def followChrist(corpse:DeadBeing):TrueBeing = corpse.resurrect().live()


Jesus said a lot of things. One that stands out and that I like to hear is "I have come that they might have life and have it more abundantly". Paul, I think, says if anyone be in Christ he is a new creature. The old has passed away the new has come. The thing is since Jesus is the resurrection and the life when you've denied yourself and taken up that cross (that is when you are dead to the world for all intents and purposes), then you can follow Jesus. You can do this because it's no longer you but the Christ in you that's alive. Paul talks a lot of salvation and grace and stuff like this. He says "...and it is no longer I who live, but Christ lives in me..." when he describes he's walking with Christ experience. In fact preceeding this he talks about dying with Christ (which I figure should be synonymous with taking up your cross).


def comeAfterChrist(deny, self)(takeUpCross)(followChrist) =
                                                     followChrist(takeUpCross(deny(self)))



The beauty of the 3 step program is that it offers life not death. It easy to stop at step 2 and cringe when you realize it's death that's been talked about. But the program does not end at step 2 it ends at 3. It ends with life. Christianity is not meant to be an easy walk but it's a worthwhile walk and it's the only walk genuinely worth walking. It's a walk of faith, hope and love (I'm beginning to sound trite). In Socrate's "The Republic", Plato talks about the impact of knowledge on courage and fear. The summary goes something like this... if you really know something you'll act out on it and people would think you courageous and vise versa. That's why for instance playing against a 10-man football team when one of them was wrongly sent off is not such a great idea. The 10 left on the pitch can sometimes surprisingly play much better than they would otherwise in the knowledge that they've been wronged and that Justice would only be done if they go down fighting the unjust decision to kick one of their own off the pitch."
Jesus puts it like this "... the truth shall set you free". Counting the cost is nothing more than knowing and accepting the truth. In fact faith comes by knowing the truth. Or as Paul puts it "faith comes by hearing and hearing by the word of God". And what's the word of God if not the truth. So why am I ranting about knowledge and truth and all what not? I know I have to start counting the cost each day. I'm not a good rep of Christ right now but I know God is still reaching out for me.

What's the point of my rant today? I don't think I can tell you. I heard this sermon today in Church and I figured like the Bereans, for once, I should go over the material again since right now I know my walk with Jesus has faltered.

There's one more thing to talk about though and it's really the hardest part to explain of it all (in fact I know I can't explain it). The thing is after all I've written so far it should be obvious that salvation is beyond me. I can't (and believe it or not you can't either) deny yourself, take up your cross and follow Christ on your own. And that my friends is the beauty of grace - I dont have to. I've just got to be willing to. I can't quite remember where but I think it says somewhere in the bible that it's God that gives us the will to do every good deed (or something of that nature). The only way to not be saved is to deny Christ outright (apparently someone has to be denied)

I've got truck loads of questions as I'm sure you do and I dont have good enough answers but "now abides faith, hope, love, these three; but the greatest of these is love". And life doesn't get any better.