aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/examples/address_book_controller.rb
blob: 9ca66125120e80f061bc4827188a9bb027b73004 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
$:.unshift(File.dirname(__FILE__) + "/../lib")

require "action_controller"
require "action_controller/test_process"

Person = Struct.new("Person", :id, :name, :email_address, :phone_number)

class AddressBookService
  attr_reader :people

  def initialize()          @people = [] end
  def create_person(data)   people.unshift(Person.new(next_person_id, data["name"], data["email_address"], data["phone_number"])) end
  def find_person(topic_id) people.select { |person| person.id == person.to_i }.first end
  def next_person_id()      people.first.id + 1 end
end

class AddressBookController < ActionController::Base
  layout "address_book/layout"
  
  before_filter :initialize_session_storage
  
  # Could also have used a proc
  # before_filter proc { |c| c.instance_variable_set("@address_book", c.session["address_book"] ||= AddressBookService.new) } 

  def index
    @title  = "Address Book"
    @people = @address_book.people
  end
  
  def person
    @person = @address_book.find_person(params[:id])
  end
  
  def create_person
    @address_book.create_person(params[:person])
    redirect_to :action => "index"
  end
    
  private
    def initialize_session_storage
      @address_book = @session["address_book"] ||= AddressBookService.new
    end
end

ActionController::Base.template_root = File.dirname(__FILE__)
# ActionController::Base.logger = Logger.new("debug.log") # Remove first comment to turn on logging in current dir

begin
  AddressBookController.process_cgi(CGI.new) if $0 == __FILE__
rescue => e
  CGI.new.out { "#{e.class}: #{e.message}" }
end