Skip to content

Instantly share code, notes, and snippets.

@marksim
Created November 24, 2009 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marksim/242013 to your computer and use it in GitHub Desktop.
Save marksim/242013 to your computer and use it in GitHub Desktop.
class ApplicationController < ActionController::Base
def load_resource
parent = nil
request.path.split("/").select{|p| !p.blank?}.to_pairs.each do |obj|
parent = set_instance_variable(obj.first.singularize, obj.last, parent)
end
model_name = params[:controller].split('/').last.singularize
begin
set_instance_variable(model_name, params[:id], parent) unless params[:action] == "index" || !instance_variable_get("@#{model_name}").nil?
rescue NameError, NoMethodError => e
instance_variable_set("@#{model_name}", model_name.to_sym)
end
end
def set_instance_variable(model_name, id_or_action, parent_obj=nil)
logger.debug("LOADING : #{model_name}/#{id_or_action}")
if id_or_action.to_i != 0
temp = parent_obj.nil? ? model_name.camelcase.constantize.find(id_or_action.to_i) : parent_obj.send(model_name.pluralize).find(id_or_action.to_i)
instance_variable_set("@#{model_name}", temp)
else
temp = parent_obj.nil? ? model_name.camelcase.constantize.new(params[model_name.to_sym]) : parent_obj.send(model_name.pluralize).build(params[model_name.to_sym])
instance_variable_set("@#{model_name}", temp)
end
temp
end
end
class Array
def to_pairs
(0..(length/2)-1).collect {|i| [self[i*2], self[i*2+1]]}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment