Module: Reststop::Helpers

Defined in:
lib/reststop.rb

Instance Method Summary collapse

Instance Method Details

#R(c, *g) ⇒ Object

Overrides Camping’s routing helper to make it possible to route RESTful resources.

Some usage examples:

R(Kittens)            # /kittens
R(Kittens, 'new')     # /kittens/new
R(Kittens, 1, 'meow') # /kittens/1/meow
R(@kitten)            # /kittens/1
R(@kitten, 'meow')    # /kittens/1/meow
R(Kittens, 'list', :colour => 'black')  # /kittens/list?colour=black

The current output format is retained, so if the current @format is :XML, the URL will be /kittens/1.xml rather than /kittens/1.

Note that your controller names might not be loaded if you’re calling R inside a view module. In that case you should use the fully qualified name (i.e. Myapp::Controllers::Kittens) or include the Controllers module into your view module.



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/reststop.rb', line 232

def R(c, *g)

	cl = c.class.name.split("::").last.pluralize
	app_name = c.class.name.split("::").first
	ctrl_cl = app_name + '::Controllers'				# @techarch : get to the Controllers using the current app
	ctrl = (app_name != 'Class') ? ctrl_cl.constantize : Controllers
	
	if ctrl.constants.include?(cl)				#@techarch updated to use new cl variable
		path = "/#{cl.underscore}/#{c.id}"
		path << ".#{@format.to_s.downcase}" if @format
		path << "/#{g.shift}" unless g.empty?
		self / path
	  elsif c.respond_to?(:restful?) && c.restful?
		base = c.name.split("::").last.underscore
		id_or_action = g.shift  
		if id_or_action.to_s =~ /\d+/			#@techarch needed a to_s after id_or_action to allow pattern matching
		  id = id_or_action
		  action = g.shift
		else
		  action = id_or_action
		end

		path = "/#{base}"
		path << "/#{id}" if id
		path << "/#{action}" if action
		path << ".#{@format.to_s.downcase}" if @format
		
		#@techarch substituted U for u=Rack::Utils
		u=Rack::Utils
		path << "?#{g.collect{|a|a.collect{|k,v| u.escape(k)+"="+u.escape(v)}.join("&")}.join("&")}" unless g.empty? # FIXME: undefined behaviour if there are multiple arguments left
		return path
	else
		_R(c, *g)
	end
end