Make a Blog with Hobo: Lifecycles

Posted by Tyler Lesmann on September 03, 2010 15:23
Tags: DRYML, Hobo, Tutorial

Sometimes we may want to not publish our blog entries to the world. They might need a little work, which we plan on doing later. So our entries need two states: published and drafted. Hobo’s lifecycles make this not too much of a chore.

First, let’s open app/models/entry.rb and define our lifecycle. These lines can go right after where we’ve defined our relations.

lifecycle do
  state :drafted, :default => true
  state :published

  transition :publish, {:drafted => :published}, :available_to => :user
  transition :unpublish, {:published => :drafted}, :available_to => :user
end

We’ve defined our two states. Our entries will default to the drafted state. There are also two transitions. Transitions define how our entry can change states. A entry can become drafted only when it is in the published state. The opposite is also true. Only the user, or author in this case, can change states. Now let’s migrate!

$ script/generate hobo_migration

States are now engaged, but we cannot change between them. We need to add some buttons. Hobo provides the extremely helpful <transition-buttons/> tag to accomplish this. Open app/views/taglibs/application.dryml and add this tag to our entry-info tag like so.

<def tag="entry-info">
  <div>
    Posted on <view:created-at/>
  </div>
  <div>
    Tags: <view:tags/>
  </div>
  <transition-buttons/>
</def>

You now have Publish and Unpublish buttons. The assortment of buttons depends on the transitions available to your current user. So we have our states and we can change between them. Now we just need to do something with those states. Let’s change the view permissions in app/models/entry.rb.

def view_permitted?(field)
  acting_user.administrator? or state == 'published'
end

Now an entry is viewable if the user is an adminstrator or if the entry is in a published state.

Comments

No comments to display