Hi, i’m curently designing an app which requires lots (and lots) of
named routes. I want it RESTful, but with paths not named after
controller. Example of what I need:
for controller User generate. user_path, user_url,
formatted_user_path … etc, but the paths would be specified by me.
Like user_path #=> /our_customer/:id, where our_customer is the custom
thing.
At first I just did LOTS of named routes, but nicely formatted it took
about 30 lines per controller and it didnt include formatted_paths. So
I refactored it into function, which is about 35 lines long, and bit
ugly. Here it comes.
8 def custom_resources mapper, options = {}
9
10 controller = options[:controller]
11 plural = options[:objects] ||
options[:object].pluralize
12 singular = options[:object] || plural.singularize
13 edit_string = options[:edit] || “edit”
14 new_string = options[:new] || “new”
15 controller_name = controller.split(’/’).last
16
17 mapper.send “#{controller_name.pluralize}index",
#GET index
18 plural,
19 :controller => controller,
20 :action => “index”,
21 :conditions => {:method => :get}
22
23 mapper.send “#{controller_name.pluralize}”, #POST
create
24 plural,
25 :controller => controller,
26 :action => “create”,
27 :conditions => {:method => :post}
28
29 mapper.send "new#{controller_name}”, #GET new
30 plural+"/#{new_string}",
31 :controller => controller,
32 :action => “new”,
33 :conditions => {:method => :get}
34
35 mapper.send “#{controller_name}”, #GET show
36 singular +"/:id",
37 :controller => controller,
38 :action => “show”,
39 :conditions => {:method => :get}
40
41 mapper.send “edit_#{controller_name}”, #GET edit
42 singular+"/:id/#{edit_string}",
43 :controller => controller,
44 :action => “edit”,
45 :conditions => {:method => :get}
46
47 mapper.send “#{controller_name}”, #PUT update
48 singular+"/:id",
49 :controller => controller,
50 :action => “update”,
51 :conditions => {:method => :put}
52
53 mapper.send “#{controller_name}”, #DELETE destroy
54 singular+"/:id",
55 :controller => controller,
56 :action => “destroy”,
57 :conditions => {:method => :delete}
58 end
59
60 custom_resources map, :controller => “admin/room”, :object
=> “place”,:new => “create_new”
this will create basic restfull routes like new_room_path #=> /places/
create_new
as you can see, it is ugly, but basicaly working. I dont want ugly
code in my app. Any sugestions? Some routing method I am missing?