Flex Application Framework for Building Social Networking Sites! Using Ruby on Rails, Flex, Cairngorm, REST, and the Ruboss Framework to Build Anything…
Hello world, again. I’ve been very busy lately developing business models and design patterns for an application we’re building, so I haven’t finished setting up that Cairngorm Flex UI Component Framework. BUT! In the meantime, I’ve studied the 5-star Flexible Rails by Peter Armstrong and it has changed my life. I am now going to be using Ruby on Rails and Flex together (even though Ruby on Rails doesn’t perform as fast as Python, it is still the best application design pattern I have ever seen and will change your life too). I just checked out Ruboss, which is a new framework for tying two of the best programming frameworks ever together, Flex and Rails. Ruboss is amazing, check it out and go through the HelloRuboss example in 2 minutes to see how fast you can get a Flex application with a Ruby on Rails backend up and running. Insane… Here is the start of what’s possible, you can take my very beginnings of a blog and transform them into something unbelievable! This is what it looks like:

HERE IS A DEMO
DOWNLOAD THE ZIP (not yet compiled in flex = smaller file)
DOWNLOAD THE COMPLETE FILE! (just cd into the directory and type ruby script/server and you’re off!)
The zip file has everything set up for connecting to a mysql database, the online demo doesn’t connect to one because then everyone would fill it up. I just commented out the SessionsController and left everything else the same, so if you want to download the source from the demo, just change that back to normal.
Anyway, I’ve been working with Ruboss on and off here and there and have added some RESTful Cairngorm capabilities to it (if Cairngorm were modified to be fully RESTful like Rails, Flex on Rails would be unstoppable!). I’ve added the options to create a Model as an “attachment” (using the great attachment_fu plugin to upload files from flex to the server) or as an authenticated user (using the crazy restful_authentication plugin). I had to learn a little about how the Plugins work in Rails, but it isn’t bad at all! Download this plugin-enhanced version of Ruboss to add account and session creation functionality, and the ability to upload files from Flex, to your HelloRuboss application!
How I modified Ruboss:
First, there are 2 parts to the plugin that I modified: rconfig and rscaffold. Each of these files are “generators” which do the bulk of the work in rails. In each of these “generator” directories, there is a “_generator.rb” file and a templates folder. The generator.rb file has two methods: initialize and manifest. The “initialize” method assigns values to all of the attributes (project name, base package name, etc.), as well as determining what all of the arguments are that you typed on the command line are going to be. I modified the rscaffold’s “initialize” method to account for different command-line arguments required for the different Plugins: restful_authentication requires two model names and nothing else, while a normal model (or one with the added “attachment” functionality) have one model name and multiple key:value pairs. I modified the “manifest” methods in both rconfig and rscaffold. Here’s what I added to the rconfig_generator.rb file (when you see m.directory, that creates a directory in the application; when you see m.template, that gets a file of that name from the “templates” directory of the generator):
rconfig_generator.rb
# Add CairngormUtils for Event Dispatching
m.directory "app/flex/com/pomodo/utils"
m.file 'CairngormUtils.as', 'app/flex/com/pomodo/utils/CairngormUtils.as'
# Add AppController and AppEvents to the project
m.template 'app_controller.as.erb',
File.join("app", "flex", base_folder, "controllers", "AppController.as")
# Add the Model Locator, which holds only application states
m.template 'model_locator.as.erb',
File.join("app", "flex", base_folder, "models", "#{project_name}ModelLocator.as")
m.template 'events.as.erb', File.join("app", "flex", base_folder, "controllers", "#{project_name}Events.as")
# Make directories for AQUA skin
m.directory 'app/flex/skins'
m.directory 'app/flex/skins/aqua'
m.directory 'app/flex/skins/aqua/fonts'
m.directory 'app/flex/skins/aqua/images'
# Add AQUA skin to path
m.file 'aqua/CSSPlus.swc', 'app/flex/skins/aqua/CSSPlus.swc'
m.file 'aqua/Aqua.css', 'app/flex/skins/aqua/Aqua.css'
m.file 'aqua/fonts/lucidaGrande.swf', 'app/flex/skins/aqua/fonts/lucidaGrande.swf'
# Add all the AQUA files the long way, I don't know how to do this shorthand yet.
%w(about_icon_up.png # rest of images...
).each do |file|
m.file "aqua/images/#{file}", "app/flex/skins/aqua/images/#{file}"
end
m.dependency 'rcontroller', @args
end
m.template 'main_box.mxml.erb', File.join('app/flex', "MainBox.mxml")
The rscaffold_generator.rb file is a bit more complicated, check out how I modified it in the source. I have added options, and each option has its own set of actionscript, mxml, and ruby file templates it implements. To add option functionality to the plugin, first go to the bottom of the generator file to the “add_options!” method and do the following:
def add_options!(opt)
opt.separator ''
opt.separator 'Options:'
#... other options
opt.on("--attachment",
"Generate signup 'activation code' confirmation via email") { |v| options[:attachment_fu] = true }
opt.on("--authenticated",
"Generate authenticated user and sessions") { |v| options[:authenticated] = true }
end
Then, in the “initialize” and “manifest” methods you can wrap block of code with either “if options[:authenticated]” or “unless options[:authenticated]” to add functionality specific to the option for the scaffold. Making Flex RESTful with RESTful Cairngorm Templates! I then modified many of the scaffold templates to implement Cairngorm’s ValueObject -> Event -> Controller -> Command -> Delegate pattern into Flex for consistent and RESTful integration into the RESTful Ruby on Rails backend. I modified the component.mxml ruboss scaffolding templates to remove the multiple RESTful methods from the view and place them into RESTful Command classes. Now, each MXML component (which is just a sample template to get you going on your project, feel free to modify it any way you wish) has just a single method, “sendData()”.
The “sendData()” method takes a RESTful string value (LIST, CREATE, UPDATE, or DESTROY), assigns the Model (aka the database object, such as “task”, “project”, or “user”) to the “data” property of the CairngormEvent and, using Peter Armstrong’s CairngormUtil from his Pomodo application, seamlessly dispatches this Event and the Application controller handles the details. Each property of the Model is assigned to text field or checkbox values, among others, but you can assign them to any user interface element you want! Now you can have multiple different views manipulating the same backend database objects using only one method in the view, the “sendData()” method. Each model is scaffolded with the default 4 RESTful events into a centralized “{ProjectName}Events” file in the Controller directory, eliminating the need for tons and tons of event classes: Cairngorm can be made RESTful no problem. The main application file (ProjectName.mxml) instantiates Cairngorm’s FrontController (into the “AppController”), and this registers all four RESTful Events for each Model with a single Command that’s named after the model. This eliminates the need to have four or more commands per model. What we are left with is, for every database model:
- one Model.as class
- one ModelCommand.as class
- a view with one “sendData()” method
- a VERY simple way to have any view talk to a backend system!
This simplifies everything and makes it so anytime you create a new Flex or Flash component, you only have to create one method that effectively and efficiently packs a Model into an Event and tells the Command which RESTful function to execute. Great. There are still a few things you will have to modify in the ComponentBox.mxml files if you have special needs, but for the most part everything is working. Here are all of the lines of code you would need type into the Terminal to create the beginnings of a Flex Blog application!!!
rails -d mysql boom
cd boom
# place the plugin-enhanced ruboss_rails_integration into vendor/plugins directory
ruby script/generate rconfig
sudo mysqladmin -u root password yourpassword
rake db:mysql:stage ADMINPASS="yourpassword" USER="root"
rake db:create:all
ruby script/generate rscaffold user has_one:blog has_many:comments,posts --authenticated
ruby script/generate rscaffold blog title:string subtitle:string body:text author:string created_at:datetime has_many:posts belongs_to:user with_user:user
ruby script/generate rscaffold post title:string subtitle:string body:text author:string published:boolean created_at:datetime has_many:comments belongs_to:blog,user with_user:user
ruby script/generate rscaffold comment title:string body:text author:string created_at:datetime belongs_to:post,blog,user with_user:user
ruby script/generate rconfig
rake db:migrate
ruby script/server
It doesn’t get much better than that! That’s 13 lines of code! Those few lines of code just created a Flex application, a Ruby on Rails application, and a MySQL database, wrote tons of lines of SQL to bring form to the database, and wired everything together into a beautiful, scalable, RESTful application. I would like to see something like that done in Python! Download my restful_authentication and attachment_fu plugin-enchanced Ruboss plugin for Ruby on Rails! DOWNLOAD!
Creating an Authenticated User in Flex using Cairngorm, Rails, and the Restful_Authentication Plugin…
In the rscaffold generator directory I have added the 2 plugin generators, attachment_fu, restful_authentication (I simply dissected out the generator from the original Plugins, added them as options to the rscaffold_generator.rb file in the “initialize” method, and transported the other files in the “lib” directory to the “lib” directory in Ruboss). To create an authenticated user, call them “person” instead of “user” if you want–but we’ll stick with user–you just type into the command line:
ruby script/generate rscaffold user --authenticated
The --authenticated option takes care of adding all the files and directories necessary in your flex and rails application to get an “person” create box (SignupBox.mxml) and a sessions box (LoginBox.mxml). Now, run the following command:
ruby script/generate rconfig
The rconfig command will rewrite all main application files, such as Blog.mxml (the main Flex file), ApplicationController.as (adding four RESTful commands for the “User.as” model, and two for the “session”, which wasn’t defined as a model in Actionscript), and the ProjectNameEvents.as class.
Extending Ruboss with Custom Commands - Using the SimpleHTTPController…
Because the Sessions object was not a defined Actionscript Model, the login data is packaged into a Cairngorm Event as a hash from the view. As such, I have used the SimpleHTTPController Ruboss class to send Session (login) data to the Rails backend and it works perfectly! So you can use the SimpleHTTPController and a Delegate if you have more complex needs. I am also wondering whether or not it will be better to, instead of using Ruboss.models.create(model, onCreate) or editedModel.create({afterCallback: onPostCreate}), to use the SimpleHTTPController and a Delegate, because sometimes this is required for the complex case, and since everything is generated with scaffolding, it may be a good option. Please leave a comment if you have any suggestions.
That leads me to this point, I haven’t yet finished mapping Attachment_Fu into Flex, but this should be easy. On the list is to finish the FileDelegate.as file (perhaps by integrating this Flex File Uploader into Ruboss and Ruby on Rails), which will allow you to upload and download multiple files to a specified directory to/from Flex/Rails. This is another example where it seems the SimpleHTTPController is necessary for creating UPLOAD_FILE and DOWNLOAD_FILE event types for attachment_fu enhanced models instead of using Ruboss.models.create(…). For now, when the --attachment_fu option is passed into the command line, everything should be set up except for the FileDelegate.as file. To be done…
Oh, and I have packaged the “Aqua” Flex skin from Fill Colors into the Ruboss plugin so the application looks amazing right off the bat! I wish there were more Flex skins available because those take forever to make nice… Anyone know of anything good?
Building a Simple Blog using Flex, Rails, and Ruboss: Okay! to get you started using this plugin-enhanced Ruboss framework, we will create a simple Blog (though only the beginnings of one…it’s not really a blog because that requires extra fine tuning) using Flex and Rails, similar to the HelloRuboss example. Create the Blog rails project in your rails projects directory, call it BOOM:
cd Documents/rails_projects
rails -d mysql boom
Now, download the plugin-enhanced Ruboss plugin and add it to the “vendor/Plugins” directory
cd blog/vendor/plugins
ls
ruboss_rails_integration
Now, run the rconfig generator to create the Flex project:
ruby script/generate rconfig
Next, configure your Rails application for using your MySQL database:
rake db:mysql:stage ADMINPASS="yourpassword" USER="root"
If you haven’t yet set a root password for MySQL, you can do so by typing the following command followed by your root password:
sudo mysqladmin -u root password yourpassword
Password:
Now create the databases for your application:
Next, go to Flex and to “Import”. Highlight “Existing Project into Workplace” and click Next. Check “Select root directory” and find the “boom” rails application directory. Click Finish. If you don’t already have “Build Automatically” selected, go to Project -> “Build All”. Now you can create your Models and Model Components. First, you may create a “user” using the restful_authentication option. Our user is going to have their own “blog”, as well as “comments” and “posts” they have created.
ruby script/generate rscaffold user has_one:blog has_many:comments,posts --authenticated
Next, create a Blog and a Comment. Our Blog belongs_to our “user”, and has_many posts. ALSO, if you want to speed up development further, add the with_user:user argument to the end of the command line for any Model (other than the authenticated user itself). This creates the ruby controller.rb classes so they get the models according to the current_user. The value user should be whatever authenticated user you created (”user”, “person”, “entity”, “human”, whatever…):
ruby script/generate rscaffold blog title:string subtitle:string body:text author:string created_at:datetime has_many:posts belongs_to:user <strong>with_user:user</strong>
ruby script/generate rscaffold post title:string subtitle:string body:text author:string published:boolean created_at:datetime has_many:comments belongs_to:blog,user <strong>with_user:user</strong>
ruby script/generate rscaffold comment title:string body:text author:string created_at:datetime belongs_to:post,blog,user <strong>with_user:user</strong>
Now run rconfig again to set up the AppController, Events, and Commands, as well as the Account Box (MainBox):
ruby script/generate rconfig
Now, before we forget, go into both the people_controller and the sessions_controller and cut out the line include AuthenticatedSystem and place it into the top of the application.rb controller. Also, comment out protect_from_forgery in the application controller for now as I have not yet dealt with the ActionController::InvalidAuthenticityToken error. Finally, add the line before_filter :login_required to the application.rb controller and you have an authenticated blogging system. Well, doesn’t look like a blog, but you can make it into one in about 5 minutes if you wanted to! We’re on our way! Someone will build a Flex Insoshi very soon I know it.
Now build Flex, check for any errors, rename/resize/reorder things, make things drag and drop ready, add some animations, and you’re ready to go! Type two last commands, the first to set up the database and the next to get the server running:
sudo rake db:migrate
ruby script/server
And type in the following URL (all the web files are stored in the public/bin folder): http://localhost:3000/bin/Boom.html Until next time…
I am going to be very busy this fall but I hope to really focus my efforts on Flex, Flash, and Ruby on Rails, especially to create bioinformatics and neurobiology and pharmacology tools.
I have become interested in JRuby on Rails because it allows you to extend Ruby’s features to include the enormous collection of sophisticated Java libraries. I would like to see someone create an JRuby on Rails API for Alfresco, then we could use an amazing Enterprise Level Content Management System in Flex and Rails without having to use Alfresco’s hacked Javascript/XML/Freemarker implementation of REST. I have also been getting into a lot of heated battles with my buddy D4 and some of our friends over using Ruby on Rails vs. Python. I have come to the conclusion that, although Python is “faster” than Ruby, there is hitherto no solid RESTful web framework written in Python (Django, being the most popular, definitely isn’t, but Pylons is trying to do that), and Python doesn’t compare in the ease of developing database-drive interactive applications with Flex and Flash.
Also, people talk about the Ruby Virtual Machine being slow and leaking memory, and this is an issue. However, it is being addressed by JRuby and Rubinius, so in a few months there should be no problem. And people also complain about Mongrel being a hack to restart the ruby virtual machine every so often so Ruby doesn’t cause your computer to crash… Well there are all kinds of ways around that, and new Ruby Servers are sprouting up everywhere (Thin, for example). So keep developing Rails applications! I have experienced that “Rails exc
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.
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.
(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:
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']} endWhile 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.
Hide Sites
If you enjoyed this post, make sure you subscribe to my RSS feed!