Marzhill Musings

Advanced Nitrogen Elements

Published On: 2009-06-16 23:33:58
In my last post I walked you through creating a basic nitrogen element. In this one I'll be covering some of the more advanced topics in nitrogen elements.
  • Event handlers and delegation
  • scripts and dynamic javascript postbacks

Nitrogen Event handlers

Nitrogen event handlers get called for any nitrogen event. A nitrogen event is specified by assigning #event to an actions attribute of a nitrogen element. The event handler in the pages module will get called with the postback of the event. Postbacks are an attribute of the event record and define the event that was fired. To handle the event you create an event function in the target module that matches your postback. For Example:
% given this event
#event{ type=click, postback={click, Id} }
% this event function would handle it
event({click, ClickedId}) ->
io:format("I [~p] was clicked", [ClickedId]) .
Erlangs pattern matching makes it especially well suited for this kind of event based programming. The one annoying limitation of this event though is that each page has to handle it individually. You could of course create a dispatching module that handled the event for you but why when nitrogen already did it for you. You can delegate an event to a specific module by setting the delegate attribute to the atom identifying that module.
% delgated event
#event{ type=click, postback={click, Id}, delegate=my_module }
You can delgate to any module you want. I use the general rule of thumb that if the event affects other elements on the page then the page module should probably handle it. If, however, the event doesn't affect other elements on the page then the element's module can handle it.

Scripts and Dynamic Postback

Now lets get make it a little more interesting. Imagine a scenario where we want to interact with some javascript on a page and dynamically generate data to send back to nitrogen. As an example lets create a silly element that grabs the mouse coordinates of a click on the element and sends that back to nitrogen. A first attempt might look something like so:
-record(silly, {?ELEMENT_BASE(element_silly)}). 
And the module is likewise simple:
-module(element_silly).
-compile(export_all).
-include("elements.hrl").
-include_lib("nitrogen/include/wf.inc").
render(ControlId, R) ->
    Id = wf:temp_id(),
    %% wait!! where do we get the loc from?!
    ClickEvent = #event{type=click, postback={click, Loc}}
    Panel = #panel{id=Id, style="width:'100px' height='100px'",
               actions=ClickEvent}, element_panel:render(Panel).

event({click, Loc}) ->
    wf:update(body, wf:f("you clicked at point: ~s", Loc)).
Well of course you spot the problem here. Since the click happens client side we don't know what to put in the Loc variable for the postback. A typical postback won't work because the data will be generated in the client and not the Nitrogen server. So how could we get the value of the coordinates sent back? The javascript to grab the coordinates with jquery looks like this:
var coord = obj('me').pageX + obj('me').pageY;
To plug that in to the click event is pretty easy since action fields in an event can hold other events or javascript or a list combining both:
Script = "var coord = obj('me').pageX + obj('me').pageY;",
ClickEvent = #event{type=click, postback={click, Loc}, actions=Script}
Now we've managed to capture the coordinates of the mouse click, but we still haven't sent it back to the server. This javascript needs a little help. What we need is a drop box. Lets enhance our element with a few helpers:
-module(element_silly).
-compile(export_all).
-include("elements.hrl").
-include_lib("nitrogen/include/wf.inc").
render(ControlId, R) ->
    Id = wf:temp_id(),
    DropBoxId = wf:temp_id(),
    MsgId = wf:temp_id(),
    Script = wf:f("var coord = obj('me').pageX + obj('me').pageY; $('~s').value = coord;",
    [DropBoxId]),
    ClickEvent = #event{type=click, postback={click, Id, MsgId},
                        actions=Script},
    Panel = #panel{id=Id, style="width:'100px'; height='100px'",
                   actions=ClickEvent, body=[#hidden{id=DropBoxId},
                                             #panel{id=MsgId}]},
    element_panel:render(Panel).

event({click, Id, Msg}) ->
    Loc = hd(wf:q(Id)),
    wf:update(Msg, wf:f("you clicked at point: ~s", Loc)).
Ahhh there we go. Now our element when clicked will:
  1. use javascript to grab the coordinates of the mouse click
  2. use javascript to store those coordinates in the hidden element
  3. use a postback to send the click event back to a nitrogen event handler with the id of the hidden element where it stored the coordinates.
We have managed to grab dynamically generated data from the client side and drop it somehwere that nitrogen can retrieve it. In the process we have used an event handler, custom javascript, and dynamic javascript postbacks. Edit: Corrected typo - June 16, 2009 at 11:40 pm

Tags:

Creating Custom Nitrogen Elements

Published On: 2009-05-22 19:05:57
Nitrogen is a web framework written in erlang for Fast AJAX Web applications. You can get Nitrogen on github Nitrogen comes with a set of useful controls, or elements in nitrogen parlance, but if you are going to do anything more fancy than a basic hello world you probably want to create some custom controls. This tutorial will walk you through the ins and outs of writing a custom element for Nitrogen. We will be creating a simple notification element similar to one I use in the Iterate! project. It will need to be able to:
  • show a message
  • have a way to dismiss it
  • and optionally expire and disappear after a configurable period of time
Every Nitrogen element has two main pieces: the Record and the Module. I'll go through each in order and walk you through creating our notification element.

The Record

The record defines all the state required to create a nitrogen element. Every record needs a certain base set of fields. These fields can be added to your record with the ?ELEMENT_BASE macro. The macro is available in the nitrogen include file wf.inc. That include file also gives you access to all the included nitrogen element records. Below you can see the record definition for our notify element. Since it is very simple in it's design it only needs the base elements and two additional fields. expire to handle our optional expiration time and default to false to indicate no expiration. msg to hold the contents of our notification.
  %Put this line in an include file for your elements
  -record(notify, {?ELEMENT_BASE(element_notify), expire=false, msg}).
  
  % put these at the top of your elements module
  -include_lib("nitrogen/include/wf.inc").
  % the above mentioned include file you may call it whatever you want
  -include("elements.inc").
  
The ELEMENT_BASE macro gives your element several fields and identifies for the element which module handles the rendering of your nitrogen element. You can specify any module you want but the convention is to name the module with element_element_name. The fields provided are: id, class, style, actions, and show_if. You can use them as you wish when it comes time to render your element. Which brings us to the module.

The Module

Of the two pieces of a nitrogen element the module does the manual labor. It renders and in some cases defines the handlers for events fired by the element. The module must export a render/2 function. This function will be called whenever nitrogen needs to render a particular instance of your element. It's two arguments are: The ControlId, and the Record defining this element instance. Of these the ControlID is probably the least understood. It is passed into your render method by nitrogen and is the assigned HTML Id for your particular element. This is important to understand because, when you call the next render method in your elements tree, you will have to pass an ID on. The rule of thumb I use is that if you want to use a different Id for your toplevel element then you can ignore the ControlId. Otherwise you should use it as the id for your toplevel element in the control. So your element's module should start out with something like this:
    -module(element_notify).
    -compile(export_all).
    -include_lib("nitrogen/include/wf.inc").
    -include("elements.hrl").
    % give us a way to inspect the fields of this elements record
    % useful in the shell where record_info isn't available
    reflect() -> record_info(fields, notify).
    % Render the custom element
    render(ControlId, R) ->
    % get a temp id for our notify element instance
    Id = ControlId,
    % Our toplevel of the element will be a panel (div)
    Panel = #panel{id=Id},
    % the element_panel module is used to render the panel element
    element_panel:render(Id, Panel),
    % Or use the alternative method:
      Module = Panel#panel.module,
      Module:render(Id, Panel).
      
Notice that the records module attribute tells us what module we should call to render the element in the alternative method. In our case we will just hardcode the module since it's known to us. So now we have a basic element that renders a div with a temp id to our page. That's not terribly useful though. We actually need this element to render our msg, and with some events attached. Lets add the code to add our message to the panels contents.
      Panel = #panel{id=Id, body=R#notify.msg},
      element_panel:render(ControlId, Panel)
      
Now whatever is in the msg attribute of our notify record will be in the body of the panel when it gets rendered. All we need is a way to dismiss it. A link should do the trick. But now we have a slight problem. In order to add our dismiss link we need to add it to the body of the Panel. but the msg is already occupying that space. We could use a list and prepend the link to the end of the list for the body but that doesn't really give us a lot of control over styling the element. what we really need is for the msg to be in an inner panel and the outer panel will hold any controls the element needs.
      Link = #link{text="dismiss"},
      InnerPanel = #panel{body=R#notify.msg},
      Panel = #panel{id=Id, body=[InnerPanel,Link]},
      element_panel:render(ControlId, Panel)
      
Our link doesn't actually dismiss the notification yet though. To add that we need to add a click event to the link. Nitrogen has a large set of events and effects available. You can find them . We will be using the click event and the hide effect.
      Event = #event{type=click,
      actions=#hide{effect=blind, target=Id}},
      Link = #link{text="dismiss", actions=Event},
      
Now our module should look something like this:
        -module(element_notify).
        -compile(export_all).
        -include_lib("nitrogen/include/wf.inc").
        -include("elements.hrl").
        % give us a way to inspect the fields of this elements record
        % useful in the shell where record_info isn't available
        reflect() -> record_info(fields, notify).
        % Render the custom element
        render(ControlId, R) ->
        % get a temp id for our notify element instance
        Id = ControlId,
        % Our toplevel of the element will be a panel (div)
        Event = #event{type=click, actions=#hide{effect=blind, target=Id}},
        Link = #link{text="dismiss", actions=Event},
        InnerPanel = #panel{body=R#notify.msg},
        Panel = #panel{id=Id, body=[InnerPanel,Link]},
        % the element_panel module is used to render the panel element
        element_panel:render(Id, Panel).
        
This is a fully functional nitrogen element. But it's missing a crucial feature to really shine. Our third feature for this element was an optional expiration for the notification. Right now you have to click dismiss to get rid of the element on the page. But sometimes we might want the element to go away after a predetermined time. This is what our expire record field is meant to determine for us. There are three possible cases for this field.
  • set to false (the default)
  • set to some integer (the number of seconds after which we want to go away)
  • set to anything else (the error condition)
This is the kind of thing erlang's case statement was made for:
          case R#notify.expire of
          false ->
          undefined;
          N when is_integer(N) ->
          % we expire in this many seconds
          wf:wire(Id, #event{type='timer', delay=N, actions=#hide{effect=blind, target=Id}});
          _ ->
          % log error and don't expire
          undefined
          end
          
          Notice the wf:wire statement. wf:wire is an alternate way to add events to a nitrogen element. Just specify the id and then the event record/javascript string you want to use. I've noticed that for events of type timer wf:wire works better than assigning them to the actions field of the event record. No idea why because I have not looked into it real closely yet. Now our module looks like this: 
          -module(element_notify).
          -compile(export_all).
          -include_lib("nitrogen/include/wf.inc").
          -include("elements.hrl").
          % give us a way to inspect the fields of this elements record
          % useful in the shell where record_info isn't available
          reflect() ->record_info(fields, notify).
          % Render the custom element
          render(_, R) ->
          % get a temp id for our notify element instance
          Id = ControlId,
          % Our toplevel of the element will be a panel (div)
          case R#notify.expire of
          false ->
          undefined;
          N when is_integer(N) ->
          % we expire in this many seconds
          wf:wire(Id, #event{type='timer', delay=N, actions=#hide{effect=blind, target=Id}});
          _ ->
          % log error and don't expire
          undefined
          end,
          Event = #event{type=click, actions=#hide{effect=blind, target=Id}},
          Link = #link{text="dismiss", actions=Event},
          InnerPanel = #panel{body=R#notify.msg},
          Panel = #panel{id=Id, body=[InnerPanel,Link]},
          % the element_panel module is used to render the panel element
          element_panel:render(ControlId, Panel).
          
We have now fulfilled all of our criteria for the element. It shows a message of our choosing. It can be dismissed with a click. And it has an optional expiration. One last thing to really polish it off though would to allow styling through the use of css classes. The ELEMENT_BASE macro we used in our record definition gives our element a class field. We can use that to set our Panel's class, allowing any user of the element to set the class as they wish like so:
            Panel = #panel{id=Id, class=["notify ", R#notify.class],
            body=[InnerPanel,Link]},
            
This gives us the final module for our custom element:
              -module(element_notify).
              -compile(export_all).
              -include_lib("nitrogen/include/wf.inc").
              -include("elements.hrl").
              % give us a way to inspect the fields of this elements record
              % useful in the shell where record_info isn't available
              reflect() -> record_info(fields, notify).
              % Render the custom element
              render(_, R) ->
              % get a temp id for our notify element instance
              Id = ControlId,
              % Our toplevel of the element will be a panel (div)
              case R#notify.expire of
              false ->
              undefined;
              N when is_integer(N) ->
              % we expire in this many seconds
              wf:wire(Id, #event{type='timer', delay=N, actions=#hide{effect=blind, target=Id}});
              _ ->
              % log error and don't expire
              undefined
              end,
              Event = #event{type=click, actions=#hide{effect=blind, target=Id}},
              Link = #link{text="dismiss", actions=Event},
              InnerPanel = #panel{body=R#notify.msg},
              Panel = #panel{id=Id, class=["notify ", R#notify.class],
              body=[InnerPanel,Link]},
              % the element_panel module is used to render the panel element
              element_panel:render(ControlId, Panel).
              
I will cover delegated events and more advanced topics in a later tutorial.

Tags:

erlang datetime utility functions

Published On: 2009-05-01 01:17:21

I have been doing some work on timeseries data in erlang for iterate graphs and
found the calendar module in stdlib to be lacking in some useful features.
So being the helpful hacker I am I created a utility module to wrap calendar
and be a little more userfriendly. May I present date_util.erl:


Tags:

Functional Programming vs OO Programming

Published On: 2009-04-26 20:52:39
I've been thinking lately about the differences between OO and FP. FP languages don't really support the OO model because of a difference in design. Some try but the "true" functional languages make no such effort and for good reason. One of the primary principles of OO programming is the black box. An object is meant to represent some entity in the system. All the state and valid actions for that entity are encapsulated in the Object and the only visibility you have into them is the interface the object provides to the outside world. Programs tend to be defined as a set of interactions between objects. FP takes a different approach. In FP data is not modifiable only transformable by functions. In FP the functions expect certain input and give back certain output for that input. They certainly don't maintain any state on their own. You can't have an object if you can't have modifiable internal state. In OO you are encouraged to group together state and activity on that state. In OO you don't think so much about state as you do about entities. Person, Car, ATM machine. All of these are commonly referenced objects in an OO tutorial or textbook. Consumers of your object are encouraged not to think about the state of a person or a car or an ATM machine. Instead they think in terms of allowable interactions with that object: Talk, Drive, Withdraw Money. Within OO code there are a huge number of possible orders of various interactions possible. So large they are just about impossible to completely test or even visualize. For example say I'm programming a person object. I've given the person object a handshake method. However, depending on the internal state of the person object that method may or may not work the same way or be supposed to be called. Maybe the person object is in a bad mood, in which case the handshake method is non-functional. How do we handle that? Hrmm, so first before calling handshake on the person object we should call the offer hand method. No wait, before we call the offer hand method, perhaps we should look at their face first to gauge their mood. This could get complicated pretty quickly. Furthermore there is nothing in the OO language that allows us to specify that the offer hand method should happen first. We obviously need to know quite a bit about the state of that person object in order to properly interact with it. Contrast that with an FP approach. This gets a little bit simpler for some people to visualize suddenly. Rather than an object, they see state and a set of possible transformations of that state. the state may be something like this. person1 mood, person2 mood. and there is an interact function. If the person1 and person2 mood is good then the interact function offers hand for handshake and the two shake hands then interact returns the new person1 mood and person2 mood. Or if the mood of one of them is bad then do some other action then return new person1 mood and person 2 mood. By placing the emphasis on the state involved the coder has reduced the problem to a set of possible transformations based on that state. In OO, an object's methods define the interface. but passing the same input to an object will not always result in the same output. Most of the time methods modify internal state and the return depends on the internal state. At any time in your code the internal state of an object must be treated as an unknown. This means the return of your objects method must also be treated as an unknown. Every object has to treat every other object like it has some sort of mental disease and could have a psychotic break any moment. It could do just about anything and if you didn't define the proper response to what they do then who knows what might happen. In FP you are encouraged to think in terms of state transformations. You are forced to consider what the state you are dealing with is and then transform that state appropriately. Since the state is of primary importance after a while FP feels more natural than OO to certain mindsets. I'm discovering that I rather like the FP mindset and miss OO less and less these days.
Glossary:
FP
Functional Programming
OO
Object Oriented

Tags:

Mnesia and Schema upgrades.

Published On: 2009-04-16 19:41:41
I had an epiphany or sorts the other day. While working on iterate I realized that I was going to need to upgrade the schema of my mnesia tables. Schema changes on databases often mean bringing down the application. At least they usually have in my experience anyway. I hate to upgrade databases. That is I did until I met erlang and mnesia. The issue is that my mnesia schema for some tables was using a user provided name for the primary key. This was fine while it was just a prototype but now it was time for it to grow up. The record describing the table had to change and all the records in a table had to change. Now no one is really using this right now so I had a choice.
  • Blow away the database and rebuild it.
  • Be all erlang'y and stuff and do it live.
Wait a minute did he just say "live"? You can't update the schema and convert all the records live. That's crazy! Ahhh but this is erlang we do things different here. Witness the glory of iterate's db_migrate_tools: Notice, the transform_stories function. It defines an anonymous fun it uses to transform the mnesia table with. Currently this function only has one signature. There is no reason it can't have more thoug. Since, erlang allows multiple signatures for anonymous functions, I can specify a signature for the next version of the mnesia table if/when it changes again. Here's the epiphany part. I can keep updating that fun with more signatures for each version of the table. Theoretically ,if I were to end up with a table that had records of multiple different historical types in it, I would be able to use this one transform function to get them all updated to the new record type. And I can do this all live without taking down the database or app. I can ship each iterate version with a module capable of updating the database live from any previous version. Now that's power that's useful. Try doing that with another platform.

Tags:

Demo of Iterate! erlang project number two is up

Published On: 2009-04-11 22:08:25

Iterate! is my Scrum style project management tool. Inspired by my dislike
for XPlanners UI. Iterate! was started about a month ago and is coded in
erlang using
mochiweb, and
nitrogen. Kick the tires and whatnot if you
want to see it in action: http://iterate.marzhillstudios.com:8001/


Tags:

Error handling (Erlang vs Other languages)

Published On: 2009-04-11 09:59:12
When I'm in Perl, Javascript, Java, or any other programming language I prefer to throw exceptions rather than return errors. This is because I've long since gotten tired of losing errors 5 calls deep in the code because I forgot to check the return and handle it. Nothing is more annoying than trying to debug a problem that is actually caused somewhere else, but you don't know because the error vanished into the that Great Heap in the Sky around about 5 calls down. You've been there before. That's when you start adding print statements followed by an exit or, if your lucky enough to have one, firing up the debugger and using break statements to narrow down the actual source of the problem. This process could take days depending on how far removed from the breaking code the actual problem is. In erlang, however, returning errors actually turns out to be useful. This is because in erlang returning errors actually has the desired effect. Usually, when you return errors in an app, it is because you don't want to kill the whole program when something breaks. What you intend is for the caller to inspect the return and do the appropriate thing. This however runs smack into the whole
programmers are fallible people, who sometimes stay up late coding at 3am, when they can hardly see the screen anymore
problem. In short you are depending on the caller to honor your contract and do the right thing even though we often do exactly the wrong thing. Even when you are the caller, sometimes you don't honor that contract. Then a month later you are doing that print statement and die or perhaps the debugger dance again. All of this because of one night when your judgement lapsed. Companies will often develop elaborate style guides, testing strategy, and code-review cultures to prevent this, but in the end most developers I know come to love throwing exceptions... unless they are coding in erlang. This is because of two elements of the erlang language design:
  • Pattern Matching
  • and Fail Fast.
In erlang returning errors requires the caller to handle them. If I try to store the return of a function and it doesn't match what I told it to expect then bang, an automatic exception. However, if I try to store the return and explicitely handle the error case then no exception is thrown. This has the wonderful effect of forcing me to think about exactly what I expect this function to return, and handling or ignoring at my choice. The big benefit is that I had to think about it. The below example illustrates the difference. The combination of Pattern Matching and Fail Fast in erlang forces the programmer to honor the contract, whether he wants to or not. This is one case where Erlang follows the "Do What I Need Not What I Want" principle in a language properly.

Tags:

Learning Erlang

Published On: 2007-09-17 03:21:21

I have taken on the task of learning erlang. I was trying to decide between
learninng Haskell, OCaml, or Erlang. OCaml, I decided against since it had too
close a similarity to C and I wanted to really stretch myself.
Haskell and Erlang both fit that bill however I found the Erlang
Documentation to be far better for someone completely new to the functional
programming world. Haskell's idea of a tutorial tried to cover too many
concepts at once and took too long to get to the hands on stuff. Also erlang
offered the opportunity to learn Distributed programming concepts along the way
so erlang it was. You can see my first erlang project
etap here.


Tags: