Forum: Ruby on Rails how would you refactor this to make it more DRY

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
(Guest)
on 2008-11-17 16:20
(Received via mailing list)
i have your typical nested resource pattern, and at most any resource
is one level deep... so for a model PurchaseOrder which is optionally
nested under Customer ive worked up this before_filter...

but the problem is, i have my parent class name hard coded into the
function... so i can either copy this to every controller (which i
really know in my heart cant be appropriate) or ask for some input...

now i know all about resource_controller and the make_resourceful
plugins... but they're all a bit too magical and over the top for my
needs - as awesome as they may be.

anyhow... heres the function.

  private
  def load_parent
    class_name = :customer
    parent_sym = "#{class_name.to_s}_id".to_sym
    parent_class = class_name.to_s.classify.constantize

    # if there is a customer_id in params then load it...
    #if not return the current controllers class, constantized so i
can do things like
    # @purchase_order = @parent.find(params[:id])
    # in my actions and have it work regardless of the presence of a
parent or not.

    @parent = params[parent_sym] ?
      parent_class.find(params[parent_sym]).send
(self.controller_name.tableize.to_sym) :
      self.controller_name.classify.constantize
  end
This topic is locked and can not be replied to.