buildr-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Alex Boisvert <alex.boisv...@gmail.com>
Subject Re: Task name which called a method
Date Fri, 29 Jan 2010 21:17:25 GMT
On Fri, Jan 29, 2010 at 7:58 AM, Andrew Moore <rp.andrew.moore@gmail.com>wrote:

> I'm a ruby newbie, and I've been using BuildR off and on for a bit
> (currently 1.3.3), but I was wondering if there is a way to access the name
> of a task that calls a method without passing an argument to that method.
> For instance:
>
> def print_task_name()
>  # print the name of the task that called this function
>  puts '['+taskName+']'
> end
>
> desc 'my-project'
> define 'my-project'
>
>  desc 'taskA'
>  task 'taskA' do
>    print_task_name
>  end
>
>  desc 'taskB'
>  task 'taskB'
>    print_task_name
>  end
>
> end #my-project
>
>
>
> My goal is that if I run:
>
> buildr my-project:taskA
>
> that the print_task_name method will print:
>
> [my-project:taskA]
>
> I've been searching through the various Rake, Buildr, and Ruby API's and
> the
> closest I've come is the core ruby 'caller' method. I've spent enough time
> trying to figure it out that it's time to ask the experts!
>
> Is what I'm wanting to do possible without adding an argument to the
> print_task_name method?
>
>
You should check out how Rote extends Rake to provide
Rake.application.current_task()

http://rote.rubyforge.org/rdoc/

The crux of the extension is the following,

module Rake

  class << self
    # Array representing current tasks being executed
    def task_stack; @tasks ||= []; end

    # Reference to current task being executed
    def current_task; task_stack.last; end
   end

  class Task
    old_execute = instance_method(:execute)

    # Execute the task, loading cached dependencies if not already
    # loaded, and handling the task stack.
    define_method(:execute) do
      begin
        Rake.task_stack << self
        # ...
        old_execute.bind(self).call({ })
      ensure
        Rake.task_stack.pop
      end
    end
  end

Hope this helps,
alex

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message