def REST(r, options = {})
crud = R "#{options[:prefix]}/#{r}/([0-9a-zA-Z]+)/([a-z_]+)(?:\.[a-z]+)?",
"#{options[:prefix]}/#{r}/([0-9a-zA-Z]+)(?:\.[a-z]+)?",
"#{options[:prefix]}/#{r}/([a-z_]+)(?:\.[a-z]+)?",
"#{options[:prefix]}/#{r}(?:\.[a-z]+)?"
crud.module_eval do
meta_def(:restful?){true}
$LOG.debug("Creating RESTful controller for #{r.inspect} using Reststop #{::Reststop::VERSION::STRING}") if $LOG
def get(id_or_custom_action = nil, custom_action = nil)
id = @input[:id] if @input[:id]
custom_action = @input[:action] if @input[:action]
if self.methods.include? id_or_custom_action
custom_action ||= id_or_custom_action
id ||= nil
else
id ||= id_or_custom_action
end
id = id.to_i if id && id =~ /^[0-9]+$/
@format = Controllers.read_format(@input, @env)
begin
if id.nil? && @input[:id].nil?
custom_action ? send(custom_action) : list
else
custom_action ? send(custom_action, id || @input[:id]) : read(id || @input[:id])
end
rescue NoMethodError => e
if e.message =~ /no such method/
return no_method(e)
else
raise e
end
rescue ActiveRecord::RecordNotFound => e
return not_found(e)
end
end
def post(custom_action = nil)
@format = Controllers.read_format(@input, @env)
custom_action ? send(custom_action) : create
end
def put(id, custom_action = nil)
id = id.to_i if id =~ /^[0-9]+$/
@format = Controllers.read_format(@input, @env)
custom_action ? send(custom_action, id || @input[:id]) : update(id || @input[:id])
end
def delete(id, custom_action = nil)
id = id.to_i if id =~ /^[0-9]+$/
@format = Controllers.read_format(@input, @env)
custom_action ? send(custom_action, id || @input[:id]) : destroy(id || @input[:id])
end
private
def _error(message, status_code = 500, e = nil)
@status = status_code
@message = message
begin
render "error_#{status_code}".intern
rescue NoMethodError
if @format.to_s == 'XML'
"<error code='#{status_code}'>#{@message}</error>"
else
out = "<strong>#{@message}</strong>"
out += "<pre style='color: #bbb'><strong>#{e.class}: #{e}</strong>\n#{e.backtrace.join("\n")}</pre>" if e
out
end
end
end
def no_method(e)
_error("No controller method responds to this route!", 501, e)
end
def not_found(e)
_error("Record not found!", 404, e)
end
end
crud
end