Author Archive for viatropos

Better than Polymorphic Associations

Preamble: Acts_as_dags may prove all you need as a plugin for all content nesting and association in Ruby on Rails. No more acts_as_polymorphs, acts_as_commentable, acts_as_taggable, has_many :through, has_many => :as ownable, etc. All of that can be easily handled using acts_as_dag and should allow you to build anything you want and have it be way more customizable than any blogging engine or wiki out there so far.

istockphoto image of network

The Story
I’ve recently been trying to design a framework abstract enough to build
all of the web 2.0 stereotypes (blog, wiki, forum, social network, e-
commerce, etc.). As such, I’ve looked a lot into how to create
classes dynamic enough to make components that are reusable in all circumstances.
The message is starting to spread around that 90% of the time you
don’t need to use Inheritance, and a lot of Plugins are starting to
make Rails apps a beautiful Composition of classes, using Modules.

However, I’ve noticed that people use a lot of the same patterns when
they design their Plugins: acts_as_taggable_on_steroids and
acts_as_commentable both basically use “Polymorphic Association” to
allow any of your custom models to be tagged or commented. A lot of
the other ones are like that too. And this is definitely NOT DRY.

I’ve also noticed that most of the open source apps (Mephisto,
Insoshi, CommunityEngine, Adva CMS, Radiant, etc.) all have their own
interpretation of how to divide up the base classes or objects to make
“a web 2.0 site”. In short, there is no consistency where there needs
to be a lot.

What it boils down to is that there are Objects and Relationships Between Objects.
Also called Nodes and Links. Or Models and Join Models. Why should there be
A BlogPost, Entry, Content, WikiPost, Comment, Article, and Document when they
are all the same thing, NODES? And why should you have a Taggable, Commentable,
Favoritable, or Attachable when they are all the same thing, LINKS?

Thinking as such, it seems that all of these web 2.0 applications can be
modeled much much better and in such a way so they are COMPLETELY
modular and scalable. How can this be done? Direct Acyclic Graphs.
How could you create a blog with comments, tags, and albums? You
could use the standard Plugins, but that is not DRY at all since they
are basically performing the same actions just with different names.
You could also just build it as you go, saying X belongs_to Y and Y has_many
X’s, but in the end your just hard coding non-DRY subclasses…

Instead, all you need are Links and Nodes. Links and Nodes.

Direct Acyclic Graph - The
(wikipedia image)

Now say you call your root node Content, and your root link Link.
Content could then be subclassed by Post, Comment, Album, etc., models
which only provide extra functionality but which are saved through STI
(Single Table Inheritance) to the database. Then using acts-as-dag,
a brilliant plugin so that your Node objects can have multiple parents
(instead of using the very limited hierarchical nested set algorithms
as seen in better_nested_set which only allow your objects one parent)
you could have a Post with many Comments (Post as the “parent” of the
Comment), while also having the privilege of being able to give those
same Comments another parent. Example:

post_one = Post.create!
post_two = Post.create!
comment_one = Comment.create!
comment_two = Comment.create!
post_one.children << comment_one
post_one.children << comment_two
post_two.children << comment_one
post_two.children << comment_two

Then in the Link class, which is basically the Join Model like
“Taggings” for acts_as_taggable_on_steroids, you say what Model is
allowed to be the parent of what other Model. So that may look
something like this:

class Link < ActiveRecord::Base
  acts_as_dag_links :polymorphic => true, :for => {’Content’ =>
['Content','Comment','Post'],
                          ‘Post’ => ['Comment']}
end

While this is a very simple example, it basically says that you don’t
need the Plugins because they aren’t DRY, or that the Plugins can be
refactored to create a generic LINKABLE one. Your Link join model does
all of the Polymorphic Associating and wiring of the Plugins PLUS
gives you the option of assigning those comments or tags to other
objects. Very cool.

This means that you can have a Post in your Blog have multiple parents
(i.e. stored in the database with a reference to “My Blog about Rails” and
“My Blog about Flex”). It also means that more complex things like taxonomies
and ontologies can be applied to web 2.0 applications, and this could
really change the way data is structured in our oh-so-common blogs.

Best,
Lance

P.S. I’m doing this because I hate Wordpress. I can’t do anything to make it look nice and do important things unless I work on it for weeks! It’s a terrible design.

Share This Post

If you enjoyed this post, make sure you subscribe to my RSS feed!

FlexPV3D - Flex UIComponents in Papervision w/ Source

Word. I’ve been trying to figure out how to make a 3D Flex UIComponent with Papervision 2 for a while now and have come up with a system that seems to work. I learned a lot from the YahooMapInPV3D AIR example, as well as a ton of other random posts. Check out this demo and see the source code:

Flex UIComponent in Papervision

Source

How it Works…
The important class is the FlexBasicView. This extends Papervision’s BasicView, making it easy to just add whatever 3D objects you want and to apply MovieMaterials to them all in one place, separate from the main Flex application. In this class, a few things happen.

First, you create a main DisplayObject3D called sceneManipulationContainer into which you are going to add your Flex-skinned Papervision 3D objects (planes, cubes, etc.) for easy manipulation. You add that to the FlexBasicView. The next thing is the most important: renderMovieClips(). This packages your UIComponents, which themselves can only be instantiated 3 children down from the main application (for now at least), into a movieClip that is used to create the MovieMaterial. Once that movieClip is made, you then pass it to the MovieMaterial. Then you create your DisplayObject3D (Plane in this case), and add your material, which is basically a thick nest => material(movie(uiComponent)).

The movie movieClip (the one used for the material) is then added to a parent movieClip, called movieParent. And this movieParent is added to the FlexBasicView.

After this, another important step must take place, and this is straight from the YahooMapInPV3D example. You first add an event listener for the plane (InteractiveScene3DEvent.OBJECT_MOVE). Then once the object is created and there is movement, this event is handled by the method skinDisplayObject3D(). What this does is align the movieClip/bundle/material into the right place on the Plane. Strange… But it works!!!

All you have to do now to add custom Flex UIComponents onto this plane is to 1) get a reference to your uiComponent which is 3 levels down from the main application, and 2) pass them into a movieClip which then is passed into the “movie” movieClip:

var newMovieClip:MovieClip() = new MovieClip();
newMovieClip(Application.application.myUIComponent);
movie.addChild(newMovieClip);

Better Design Patterns for the Future
I would like to have separated this FlexBasicView into more well defined classes, but I don’t have the time right now to dig that deep. Basically, you would create a UIComponentMaterial class that did all the movieClip configuration, and this would take in a UIComponent from the 3-level-down location. To make this so you don’t have to do Application.application.myComponent, it would be nice to create this on the main app, and to have a method like UIComponentMaterial.addUIComponent(myComponent) that took care of everything for you. However, the UIComponent you use for the MovieMaterial skin must also have a reference to the DisplayObject3D in order to become the correct width and height and whatnot, so this might get tricky. John Grden’s WinterWonderland screencast, which is a pretty hardcore example of what papervision can do, has an excellent example of how to let the movieClip used to make a MovieMaterial have reference to its parent MovieMaterial AND the DisplayObject3D it’s skinning. It’s pretty neat, and maybe that can be applied in this situation.

The goal would be a scenario something like this:

-In the main application mxml file, add the 2 canvases and make the 3rd layer “FlexBasicView”

<Application>
	<Canvas id="pv3dContainer">
		<me:FlexBasicView id="flexBasicView">
		</me:FlexBasicView>
	</Canvas>
</Application>

-Then it would be nice to be able to just put some MXML nested in the FlexBasicView tag that created Papervision components skinned with your UIComponent. Something like this:

<Application>
	<Canvas id="pv3dContainer">
		<me:FlexBasicView id="flexBasicView">
			<me:sceneManipulationContainer>
				<me:FlexPlane id="extendsDisplayObject3D" material="{myUIComponent}">
				</me:FlexPlane>
				<me:FlexCube id="alsoExtendsDisplayObject3D">
					<me:MaterialList>
						<Lots of Materials with UIComponent references>
					</me:MaterialList>
				</me:FlexCube>
			</me:sceneManipulationContainer>
		</me:FlexBasicView>
		<Canvas id="2ndLayer">
			<me:CommentBox id="myCommentUIComponent"/>
			<me:ProfileBox id="myProfileUIComponent"/>
			<me:CustomBox id="myUIComponent"/>
		</Canvas>
	</Canvas>
</Application>

Another way of doing that would be to stop at the level, and then do the rest in Actionscript so you could have a little more control. If any of you guys have any ideas or suggestions, please comment!

Now for the glitches…
Some things I’ve noticed.

  • 1) You’ll notice I have a custom Font in the assets folder. This is because, for some reason, the Text appears in the top left corner if you use Flex’s default font. The main glitch you get in all cases is something unexpected appearing in the left corner.
  • 2) If you nest things too deeply, you will get a white box appearing in the top left corner. This seems to be somewhat arbitrary and I haven’t pinpointed the reason why it happens. For example, if you add another nested DataGrid into the CommentBox that comes with the source code, nesting it into a FormItem (just for testing purposes), the white box glitch appears. Maybe I am missing something about the way Flex UIComponents are supposed to be nested? This also happens in more normal cases.
  • 3) Sometimes there are differences between Flex Boxes vs. Panels/Canvases. I’ve had HBoxes show the white box in the corner too…
  • 4) In the renderMovieClips() function in FlexBasicView, there are many ways to addChild the movieClips. Sometimes it works with just one. Sometimes every nested UIComponent should get their own newMovieClip, and then you add all of them in the order you want to a main movieClip as shown above.
  • 5) Things with Popups don’t work well, such as the ComboBox. And there’s no way to capture the Popup from that class unless you change either the PopupManager or create a CustomComboBox. You can grab the Combobox.dropdown, but it also tweens, so it’s sketchy.
  • 6) The scrollbar is jumpy.
  • 7) In some situations you can comment out //movieParent.addChild(movie) and //addChild(movieParent) and you’ll still see it work, in other situations you won’t.
  • 8) If the width of your component is not a % (like width=”100%”), it may create that white box in the corner. That is, if your width is an absolute value.
  • 9) Sometimes, if you add your UIComponent in MXML it won’t work. So you just do it in actionscript. But sometimes you can also add your UIComponent in MXML, and also say “addChild(myComponent)” in actionscript at it will work.

Flex and Papervision Don’t Mix Well…
But with enough time, it’s definitely possible

As you can see, this is very rough; there’s no real system for making Papervision Flex UIComponents yet, though I wish there was! Maybe the guys from OutSmart can shed some of their wisdom… I have just found that there are no examples on the internet of this being successfully done, and done in such a way that you can switch out components easily and apply it to different DisplayObject3D’s. So I’m throwin this out there for everyone to mess around with ;)

Needless to say, Flex doesn’t play very well with Papervision, at least in my experience. Sure there are a few examples on the web of using Sprites in Flex, like the 3d product gallery, but the real goal is to have 3D Flex UIComponents. If anyone knows of a better way to do this, by all means let us know. I’m looking forward to seeing how this can be done better.

Cheers,
Lance

Share This Post

If you enjoyed this post, make sure you subscribe to my RSS feed!

Ruboss - Overview of Architecture and Magic

Architecture of the Ruboss Application

The Flex Part:

Let’s first take a look at the Flex front end. The main goal of an Enterprise Flex application is to send and receive data to/from a server. Data may be sent in three main formats: XML, JSON, or AMF. XML as a data transfer format is the simplest to understand and most widely used, so that’s what we will use here. JSON is an up and coming format that uses a hash of key:value pairs to transfer data and is thus faster than XML, which can become bulky. AMF is Adobe’s binary data transfer format (Action Message Format) and is by far the fastest to transfer data, but we will save that for later.

So our goal is send XML data from Flex (or Flash, it’s just Actionscript) out to a server so a language such as Ruby, PHP, or Python can act do something with it (access a database, store it on a remote hard drive, etc.); we are using Ruby. Once Ruby does its thing to the data, it sends back data to Flex in any format (and it can be a different format). Flex then displays the changes on the user interface. All of this data transfer occurs RESTfully, that is, occurs over HTTP using only GET, POST, UPDATE, and DELETE.

So what is happening???

Enter Cairngorm. Enter RESTful Cairngorm. When we type text into the Post text input boxes and check the check boxes in the view, and click “Save”, here’s what happens, in a nutshell…

View:
-Text and checkbox data are assigned to the attributes of the Post model. Our Post model has the attributes title, subtitle, body, author, published boolean, and created_at date.
-The button click executes a simple function and passes it a RESTful Event type: sendData(Flexible_blogEvents.CREATE_POST).
-The sendData(eventType) method dispatches a Cairngorm Event (a regular Event with the added data:* parameter that we use to pass in the Post model) of eventType Flexible_blogEvents.CREATE_POST.

Controller:
-A centralized FlexibleBlogEvents class keeps a list of all the RESTful Events in the application. This eliminates the need to have a potentially unlimited number of similar event classes.
-The AppController class is instantiated in the Flexible_blog.mxml main Application MXML file. This allows all events to be listened to and acted upon from the centralized main application file. The AppController executes the appropriate Command based on the Event it receives, and passes the Command the Event along with its data. In our case, the PostCommand would be passed the CairngormEvent of type Flexible_blogEvents.CREATE_POST and executed.
-The PostCommand’s execute() method is called, assigns the event.data value (the Post model and the values it was assigned from the view) to a variable called editedPost of type Post, and calls the corresponding createPost() RESTful method. The createPost() method then does some neat Ruboss magic. Where you would normally have to create a delegate and then do a complicated HTTPService request, Ruboss made it so all you need to do is call the create() method on the editedPost model and pass it a callback function. We do this with the line: editedPost.create({afterCallback: onPostCreate}).
-All of the complicated data transferring over the server to Rails and ultimately to MySQL is handled by some Ruboss magic we don’t have to worry about, but I’ll go a little in a bit anyway.

Model:
-The model extends the RubossModel class, allowing us to call RESTful methods directly from the model. The model is also an Actionscript representation of the database entity, so it has a reference to all of its attributes and its relationships to other entities (belongs_to, has_one, has_many). Our Post model has the attributes title, subtitle, body, author, published, and createdAt.
-I’ve also included a ModelLocator that is instantiated anywhere we want to change the view state of the application (say, from the login screen to the main application).

So now we have a Flex application that follows a RESTful MVC Architecture. Cairngorm was made RESTful by 1) creating a single and centralized Events class that is really just a collection of strings, and 2) creating a single Command for every Model that executes either of four RESTful methods based on the Event type (done by Ruboss magic). Now you hardly have to think about how to connect a Flex UIComponent to a database.

Ruboss’s Flex Magic:

Ruboss effectively eliminates the need to manually use Flex’s HTTPService class to talk to transfer data across a server. It does so through its RubossModelController class. The RubossModelController’s main job is to call the appropriate RESTful methods on a model. So if you send an event type Flexible_blogEvents.CREATE_POST, it will execute the create() method on the Post model in the RubossModelController. each RESTful method has reference to the targetServiceId (HTTP, AMF, etc.), the metadata of the model as it transfers across the server, and a a callback object to handle the server response. All the hard stuff is done for you! Note, only the “index” and “show” methods dispatch a propertyChange event, allowing Flex to update its view.

Another important Ruboss class is the SimpleHTTPController. It has one method called send() that instantiates Flex’s HTTPService, assigns the service an HTTP method, and uses an AsyncToken to send the HTTP request to the server. This is how it is used, for example, in creating a “session” from the SessionsCommand.as file:

public function createSession():void {
     // the "session" is the url we invoke in rails.
	new SimpleHTTPController().send("session", {login: session.login,
	password: session.password}, SimpleHTTPController.POST, this);
     // "this" is the "responder"
}

Because Flex and Actionscript only support two HTTP methods (GET and POST), Ruboss does some magic to add DELETE and UPDATE. Pretty neat! To see an example of how to use the SimpleHTTPController class in a Command, check out how the SessionsCommand was implemented.

Now we have the RubossModel class. This is a bindable class that all models extend (like our Post model) that 1) creates variables for each model attribute you typed into the command line, and 2) allows you to call RESTful methods directly from itself. Again, the “show” method dispatches a propertyChange event to update Flex’s view.

In order to clone a model, use the RubossUtils class: RubossUtils.clone(model). It also has functions to see if the model belongs_to another model, or has_many or has_one of some other model. There’s some great stuff in this class.

Finally, we have the main Ruboss class. The only two things you need to know now about this class are that it has a reference to the ModelsCollection class through the variable “models”, and the “filter()” method. When you call the “create()” method on your Post model (or any other of the RESTful methods), the RubossModel class executes the following:
Ruboss.models.create(editedPost, onPostCreate). Ruboss handles a lot of the repetitive coding was handled for us in the background. You use the filter method if you want to provide different views of the same model. Implement it like this:

Ruboss.filter(Ruboss.models.index(Post), yourFilterFunction);

There is also an AirServiceProvider class, but we will do that sometime later. That’s it for the Ruboss magic! Ruboss takes care of all the HTTPService requests in the background, making it so we can just call the method we want from the model. In addition, the Ruboss Framework is extremely elegant and only consists of 22 classes. Nice.

The Rails Part…

So now we have XML data (or JSON or AMF) that has bend sent from Flex as an HTTP request, and our Rails side of the application needs to handle it. No problem. This works because of Rails “routing” and its MVC architecture.

When we called the editedPost.create() method, an HTTPService request was sent that was packaged with a URL to manipulate our database Post model. It sends off a URL called “posts” along with the method “POST”. The URL “posts” tells you that we are using the posts_controller. When Rails receives this URL request and HTTP method, it executes the “create” method in Ruby.

Here is the “create” method that Ruboss scaffolds for us:

# POST /posts
# POST /posts.xml
# POST /posts.fxml
def create
  @post = Posts.new(params[:post])
 
  respond_to do |format|
    if @post.save
      flash[:notice] = 'Post was successfully created.'
      format.html { redirect_to(@post) }
      format.xml  { render :xml => @post, :status => :created, :location => @post }
      format.fxml  { render :xml => @post }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      format.fxml  { render :xml => @post.errors }
    end
  end
end

Every Ruby on Rails controller class looks the same, thanks to the excellent design patterns and scaffolding. First we create a new post, then the respond_to do block saves the Post and renders the result as either HTML or XML. I’m guessing the FXML format is “Flex XML” and basically reformats the XML to get rid of dashes and subtle formatting differences between Flex and Ruby on Rails. All of that is happening in the background. To see how it actually works, go to the file in the vendor/Plugins/ruboss_rails_integration/lib directory called ruboss_rails_integration.rb. This is where they register the FXML mimetype and do all the conversions and such.

Here’s what happens in Ruby on Rails in a nutshell…

View
- Ruboss doesn’t use Rails’ ActionView templates because of Flex. So our View is Flex, and it sends its data as XML (or JSON or AMF).

Controller
-URL from the Flex HTTPService request is routed to the appropriate controller (posts_controller in this case) via the routes.rb file.
-The appropriate controller method is executed (”create” in this case). This access and manipulates the database object using, for instance, Post.find(:id) for “show” or Post.new(params[:post]) for “create”.
-The resulting data is returned to the controller and then formatted to XML or any other specified format. This is then read by Flex.

Model
-In its most basic form, the model has just references to the objects it associates with (belongs_to, has_one, has_many). Can have other methods if you want to organize the data a certain way.
-A Migration file is created (create_posts) that allows for easy integration of the model into the database.

That’s it for now.

ToDo’s:

- Create a scale-proof Ruby on Rails server cluster to embed into Ruboss (Heroku?)
- Create Flex MXML templates for a Blog, Comments, Search (with Sphinx) Forum, Profile, Wiki, PhotoGallery, and Podcast Viewer.

Share This Post