Archive for Plugins

FirebugLogger Released

So I finally decided to release one of my toy Rails plugin to the public, hoping that someone besides me can benefit from it.

My Rails development consists of using multiple screens, with one running tail -f logs/development.log . Now the problem I found with Rails development is that the logs were hard to read/decipher through. Sure you can trim them in various ways, but when you want things fast and instant, its a bit tedious. Especially when you are debugging a page, and breakpoints are not available to you. (Darn you v1.8.5!)

One of my favorite tools for web development is Firebug, a Firefox extension that makes web development a whole lot easier. Its terrific for debugging JavaScript and Ajax, modifying the DOM tree and bending it to your will, and generally all around awesome!

I decided to create a simple plugin that would log things to the Firebug console. Actually its very simple, just save the log calls and output them to the view! It’s more like a hack! But hey it does its job.

Example

Now FirebugLogger isn’t the same as the default Logger. In the Controller a new object, firebug, is exposed for you to submit your logs.

Inside your View you just have to place:

After it is all baked and done, here is a screenshot for you:
FirebugLogger

If you are familiar with PHP development, then you’d probably know about the echo/var_dump type of debugging. But you can’t do that in Rails, thus the intention for this plugin was something like that. At least it doesn’t break your beautiful pages :).

But it is also smart in that it won’t display anything in your test or production environments. (You could if wanted to). So you can leave the logs there without worrying too much.

I opted not to mix it with the default Logger as I didn’t want the ActionController or ActiveRecord logs filling up the JavaScript console! If I wanted that I could just tail the logs, which I already do.

Now FirebugLogger does not seek to replace breakpointer, nor is it supposed to replace the default Logger.

You can find out more information about FirebugLogger here. But there isn’t really much more to it.

Note: You don’t need Firefox to you use Firebug, you can replace it Firebug Lite.

Here are some more screenshots of it running using Firebug Lite in Safari, Internet Explorer 7, and Opera.
FirebugLogger - Safari FirebugLogger IE7 FirebugLogger Opera

Installation

Installing FirebugLogger is just like installing any other plugin:
./script/plugin install http://svn.aizatto.com/firebug_logger/trunk/

Or if your project is in subversion you can add the -x flag.

License

FirebugLogger is released under the MIT license.

Comments (5)

Experimenting with Haml

HAML has made a bit of noise in the Rails scene with its approach to templating. Just have a look further down.

Embedded Ruby Code (.rhtml):

Haml (.haml):

From the HAML site:

Haml is based on one primary principal. Markup should be beautiful.

Now beautiful is subjective, and it takes a while to get used to HAML actually. Took me a while to get used to Ruby code as well.

Sass is also bundled with Haml. While Haml is the counterpart for the templating, Sass is the counterpart for stylesheets.

I understood why both Haml and Sass were created, and now I wouldn’t recommend them per se but its nice to have options. I am replacing pieces of my embedded ruby code to Haml, but I haven’ t moved a project 100% over. (I wonder if its even possible?). Its nice in that it removes alot of redundancy from your templates, and it sort of beautifies the code by removing all the sharp angly brackets, so you can’t cut yourself writing (X)HTML!

Now I won’t cover Sass as well, I don’t really use it. Faster development? Well my stylesheets haven’t had a need for the problems that Sass was created to solve. Constants in CSS, nexted rules, arithmetic, dynamic colors.

Installing Haml and Sass

Now the installation suggests to install you do it via the normal:
./script/plugin install http://svn.hamptoncatlin.com/haml/tags/stable

But that ain’t cool! It creates a folder called stable in my plugins directory that:

  1. could clash with other plugins because of its vague name
  2. doesn’t give me an idea of what the plugin is for

So I cheated and pulled via subversion:
svn co http://svn.hamptoncatlin.com/haml/tags/stable ./vendor/plugins/haml

Vim Support

So it appears that there is Haml syntax support for Vim, which is a major plus for me, else I might opt not to use it. Syntax highlighting is very important to me, as it makes life a whole lot easier.

Some things are broken though, the regex to select the class or id after the element doesn’t accept underscores or dashes (-). Just pull up the syntax file:
Lines 37 and 38:

syn region  hamlCssClass    start="\.[\-_a-zA-Z0-9]*[=~]" end="$" contains=@rubyTop,hamlRubyCode,hamlRubyHash
syn match   hamlCssClass    "\.[\-_a-zA-Z0-9]*"

Lines 40 and 41:

syn region  hamlCssClass    start="\.[\-_a-zA-Z0-9]*[=~]" end="$" contains=@rubyTop,hamlRubyCode,hamlRubyHash
syn match   hamlCssClass    "\.[\-_a-zA-Z0-9]*"

Easy html2haml Conversion

Actually when you install Haml via the Ruby Gem (gem install haml Terminal) it installs a script called html2haml, which can nicely convert your html to haml :). Beware though when using .rhtml it leaves the <% %> in place, and some other things, but its a good start. Plus you don’t have to do all the work in converting.

Notes

Now the Haml site does have examples, but it doesn’t cover everything.

Embedded Ruby Code:

Equivalent Haml Code:

Important Notes:
Here are the ones that you may not notice instantly.

  • a minus/dash at the start of the line represses the output of that line. (Line 3, 11)
  • Iterating through lists is still possible, but do note that you do not need to specify end. (Line 3). All blocks work this way, including the form_tag.
  • For dynamic ids and classes the arguments to a tag actually accepts a hash, and the values are interpreted. In Line 4 I use the user id and a odd_or_even method. You do not need to quote them in strings. I only quoted them because I wanted the strings ‘user’ and ‘row’ to be present.

General Notes: Here are the things which are expected to happen, but just noted.

  • The indentation is very important, it indicates how the code should be nested.
  • HTML tags are now reduced to %tag. (Lines 1, 2, 4, 5)
  • Only when the text you want displayed is not nested with other elements you can place it after that tag. (Line 1, 5, 6)
  • When nested you have to place it on the next line (Line 8 )
  • Instance variables are still accessible. (Line 3)
  • Similar to CSS, to specify ids and classes you append to the tag either a hash followed by the id (Line 2) or a period followed by the class name(Line 5, 6). Multiple classes can be joined together by appending the classes, ie: %ul.textCenter.horizontalList
  • To output the value of a variable you use the equals operator (=) at the start of a line, a tags id and class declarations (Line 5, 6). It can also be used on its own, it does not create a div (Line 9)
  • Due to the prevalence of the div tag, you can omit it directly (ie: %div) and just specify either an id or a class. (Line 7) to easily divide up my list items.
  • When the equals operator (=) is used on its own, it does not create a div (Line 9)
  • Helper methods are still available and made public to the view. (Line 9, 11)

Comments (1)

Ruby on Rails Finite State Machine Plugin: acts_as_state_machine

A finite state machine is a model of behavior with a finite number of states, interconnected via transitions and events.

In this guide, I will introduce you to a Ruby on Rails plugin to easily recreate a Finite State Machine with your models. The plugin we will be using is the acts_as_state_machine, which as you can see has very sparse documentation. Google does pull up some results, but not good enough, at least for beginners.

Why would you use a Finite State Machine?

For starters, if your model has a finite number of various states, and you want an easy way for callbacks to be done. Callbacks can be used to notify, validate, increment, anything, when your model changes state.

Installing acts_as_state_machine

Go to the root folder of your Rails application and execute:

./script/plugin install \
    http://elitists.textdriven.com/svn/plugins/acts_as_state_machine/trunk/

Warning: Split over two lines as it was really long.
Don’t forget if your project is under subversion, you can use the -x flag to externally link to the plugin

Using acts_as_state_machine

Note: The plugin makes an assumption that the state of your model is saved in field called state. This can be replaced by adding the additional option :column => 'field'.
Warning: If you are using a model that stores addresses, be weary of a field called “state”. You can spend hours wondering why things aren’t working like they should be.

Personal Preference: I like to describe the states my models are in with as an adjective, and the event as a verb.

Notice how in line 2 we explicitly state the initial state of the model. In lines 3 to 6, we indicate the various states the Person may be in.

There is a peculiar behavior when creating objects via new, in that the model’s state is not specified. It will only be specified when saving the new record. One solution is to specify the default state from within the migration. The other solution then is to call create.

Example:

Note: If you didn’t notice the trend, the method to test if the model is in the state, is to append the state with a question mark: "state?"

The events you specified also creates instance methods, to transition the model from one state to another.

The following instance methods were created:

Note: The instance methods created follow the pattern "event!"

Events

Note: By calling any event, you also call ActiveRecord::Base.save. For when it fails, it only returns false. You can guard yourself by calling valid? and save!

Events help you to transition from one state to another. So suppose your person is sleeping, and you want him to shower, well we’ll just call shower!.

Events can help your organize the flow of your model. But they can get more powerful with callbacks.

Callbacks

The state also comes with a few callbacks that can be used.

Callbacks are called when the model is transitioning into the specified state.

Note:

  • Callbacks can be either a symbol or a Proc. If used as a symbol, the instance method of the model will be called
  • The callbacks act differently if the model is a new record and hasn’t been saved, versus an already saved model.

When put into consideration with ActiveRecord’s callbacks, a new record’s callback would look like this:

  • ActiveRecord::Base.before_save
  • ActiveRecord::Base.save
  • acts_as_state_machine :enter sleeping
  • acts_as_state_machine :after sleeping
  • ActiveRecord::Base.after_save

When the model is no longer a new record, the callbacks execute as follows, if I had called the shower! method.

  • acts_as_state_machine :enter showering
  • ActiveRecord::Base.before_save
  • ActiveRecord::Base.save
  • ActiveRecord::Base.after_save
  • acts_as_state_machine :after showering
  • acts_as_state_machine :exit sleeping

Guarding States

But how about if you want some sort of validation for a transition. You know, just to ensure data integrity.

The transition can be guarded by specifying a :guard option, with either a symbol or Proc (similar to the Callbacks). The method or Proc has to return true to proceed with the transition, else it will fail silently.

Conclusion

Well thats the basics, and as much as acts_as_state_machine does.

Any tips, tricks and or pointers? Leave them as comments.

Or are there any other interesting plugins you’d like me to explore?

Comments (27)