So you are adding comments to your app and you would like to provide live preview functionality. There is a simple and effective way to do it.
Lets start by creating a new comment form:
New Comment
<-% form_for(@comment) do |f| %>
<-%= render :partial => 'form', :locals => {:f => f} %>
<-%= f.submit "Save Comment" %>
<-% end %>
Now we need to write an observer to watch our form for changes. It’s important that your form has an unique id, such as “new_comment”.
<-%= observe_form "new_comment",
:frequency => 2,
:update => "live_preview",
:complete => "Element.show('live_preview')",
:url => { :controller => 'comments', :action => 'preview' } %>
Note in the observe_form method above you tell it update “live-preview” every 2 seconds. Create a div with an id of live_preview and set it’s display property to none.
Next create a preview method in your comments controller
def preview render :layout => false end
The next step is to create a view that will be used to display your live preview data. I called my view preview.html.erb.
Your Comment: <-%= params[:comment][:body] %>
You will also need to add a route if you are using rails edge for the preview action:
map.preview 'comment_preview', :controller => 'comments', :action => 'preview'
That should be enough to setup a simple live preview.
Enjoy!
Model observers are useful for when you are trying to extend the class with functionally that is not directly connected to the DB model.
For example, you would like the app to send out an welcome email when a new user signs up. Emailing the member has no connection to the database table you are trying to model.
So you could create a MemberObserber as such:
ruby script/generate observer Member
That generator will create a file called member_observer.rb inside you app/models folder, which will look something like this:
class MemberObserver < ActiveRecord::Observer end
You may now add a after_create method inside the class above. That method will be called after a member record is created.
class MemberObserver < ActiveRecord::Observer
def after_save(member)
AuthenticationMailer.deliver_welcome_email(member)
end
end
If you name your observer the same as you model, rails will automatically set it to observe your model. You can however call it something different and manually specify what to observe, as such:
class MailerObserver < ActiveRecord::Observer observe Member observer Reminder end
Enjoy!
Well, after 48 hours of coding, we finally finished our app.
We decided to create a recipe/shopping manager called Tasty Planner.
Tasty Planner was built using Ruby on Rails in forty eight hours by a team of three dedicated code monkeys, Josh Owens, Chris Saylor, Bruno Miranda and designed by Kevin Burg. Give Tasty Planner a try, like it? We would appreciate it if you registered and voted for us on the Rumble site.
We will continue to improve the application in the next, week, you can expect to see lots of improvements.
Don’t forget to vote for us, thanks!

