Extension Examples
Back in time (1 more)
Home | Pages | Files

Extending Tickets

This example extensions adds an estimated-hours option to tickets.

Create a new extension folder
cd extensions/
mkdir tickets_extended
cd tickets_extended/
Create the required folders and the extension loader
mkdir ext/
mkdir migrate/
mkdir -p views/tickets_extended/
touch ext_info.rb
Add the migration

Create/open migrate/20090528180148_add_hours_column_to_tickets.rb with an editor and add the following content:

class AddHoursColumnToTickets < ActiveRecord::Migration

  def self.up
    add_column 'tickets', 'estimated_hours', :integer, :null => false, :default => 0
  end

  def self.down
    remove_column 'tickets', 'estimated_hours'
  end

end
Extend the Ticket model

Create/open ext/ticket.rb with an editor and add the following content:

Ticket.class_eval do 

  # Make sure estimated hours are ALWAYS numeric
  validates_numericality_of :estimated_hours, 
    :greater_than_or_equal_to => 0,
    :only_integer => true  

  # Make sure estimated hours are user-writeable
  attr_accessible :estimated_hours

end
Extend the TicketChange model

To trace changes to the estimated_hours column, we also need to extend the TicketChange Open ext/ticket_change.rb, add:

TicketChange.class_eval do 

  # Make sure we are able to accept changes to estimated_hours and forward 
  # those to the parent ticket
  delegate :estimated_hours, :estimated_hours=, :to => :ticket
  attr_accessible :estimated_hours

  private

    # Before saving, store the change (previous value -> new value)
    def store_changes_for_estimated_hours!(result, old_value, new_value)
      change = hash_for_ticket_change(old_value, new_value)
      result[N_('Estimated hours')] = change if change
    end  

end
Add the view partial

Open views/tickets_extended/_ticket_options.html.erb, add the following lines:

<tr>
  <th><%= f.label :estimated_hours, _('Hours') + ':' %></th>
  <td><%= f.text_field :estimated_hours, :size => 5 %></td>
  <th>&nbsp;</th>
  <td>&nbsp;</td>
</tr>
Activate partial

Open ext_info.rb, add this line:

RetroEM::Views.register_extension('tickets_extended/ticket_options', :ticket, :options, :middle)
Done!

Download the full example