Access a controller's instance variable from a block using instance_eval

I'm making a breadcrumb module for my Ruby on Rails application, but I wanted a specific syntax - which I thought was good looking and more intuitive for Rails developers.

Here's the deal:

class WelcomeController < ApplicationController

  breadcrumb_for :index, :text => 'Home', :href => -> { root_path }

  def index
  end
end

See, it's neat.

You can safely ignore the everything else but that proc - what I assign to the :href key.

I use instance_eval so that when the proc is evaluated it has access to the root_path helper.

And it worked. The example above is okay. BUT then I wanted to use an instance variable and that didn't work.

Like this:

class WelcomeController < ApplicationController

  breadcrumb_for :index, :text => 'Home', :href => -> { @path }

  def index
    @path = root_path
  end
end

Now, in that proc context @path is nil.

What should I do so I can access the instance variables from the block ?

Below is all the code of my module. Note that when I "process" the blocks and use instance_eval (aka call my module's #breadcrumb) the action should already be evaluated so the instance variable @path should already exist.

module Breadcrumb
  extend ActiveSupport::Concern

  included do
    cattr_accessor(:_breadcrumb) { [] }

    helper_method :breadcrumb

    def self.breadcrumb_for(*args)
      options = args.pop
      _breadcrumb.push([args, options])
    end
  end

  def breadcrumb
    @breadcrumb ||= self._breadcrumb.map do |item|
      puts item

      if item[0].include?(params[:action]) || item[0][0] == '*'

        text, href = item[1].values_at(:text, :href)

        if text.respond_to?(:call)
          text = instance_eval(&text)
        end

        if href.respond_to?(:call)
          href = instance_eval(&href)
        end

        [text, href]
      end
    end
  end
end

Answers


Oh no. I'm ashamed to say but it was my mistake. The code above works just fine, I was using different variable names in my application, not shown in the excerpt I used in the question.

Thanks anyway, I'll left it here for reference.


Need Your Help

Cron job for big data

php xml rss cron

I'm working on a social network like Friendfeed. When user add his feed links, I use a cron job to parse each user feed. Is this possible with large number of users, like parsing 10.000 links each ...

PHP Launch script after background process completes?

php process background-process pdf2swf

I am converting a PDF with PDF2SWF and Indexing with XPDF.. with exec.. only this requires the execution time to be really high.