Search code examples
ruby-on-railsrubybreadcrumbs

Converting a string into a controller method call


I'm trying to create a generic breadcrumbs method in my application controller to assign the breadcrumbs based on the current controller. If I wanted the breadcrumbs for the index of 'Thing', I would need in the view:

<%= breadcrumb :things, things %>

And for edit or show:

<%= breadcrumb :thing, thing %>

Where things is a method in the things controller that returns all things, and thing is a method returning the relevant thing.Both are exposed, and I have in my application layout:

<%= breadcrumb crumb, crumb_resource %>

And in my application controller:

def crumb
  return controller_name.singularize.to_sym if edit_or_show_action
  controller_name.to_sym
end

def crumb_resource
  resource = controller_name
  resource = controller_name.singularize if edit_or_show_action
end

def edit_or_show_action
  action_name == 'edit' || 'show'
end

This obviously returns a string for crumb_resource, rather than the call to the controller method. From what I can find I believe it has something to do with send, however

controller.send(resource)

obviously doesn't work. How can I convert the string that is returned into a controller method call?


Solution

  • If you're using Gretel, then I think what you might be looking for is this:

    def crumb_resource
      resource = controller_name
      resource = controller_name.singularize if edit_or_show_action
    
      self.instance_variable_get("@#{resource}")
    end
    

    This is assuming you have stored the relevant resource into @resource_name during the edit/show/index action.