Ruby - Thor execute a specific Task first
Asked Answered
D

2

8

Is it possible to call a specific task first, when i run a thor task?

my Thorfile:

class Db < Thor

  desc "show_Version", "some description ..."
  def show_version # <= needs a database connection
    puts ActiveRecord::Migrator.current_version
  end

  private

  def connect_to_database # <= call this always when a task from this file is executed
    # connect here to database
  end

end

I could write the "connect_to_database" method in every task but that seems not very DRY.

Dodson answered 11/11, 2010 at 9:21 Comment(0)
G
12

You can use invoke to run other tasks:

def show_version
  invoke :connect_to_database
  # ...
end

That will also make sure that they are run only once, otherwise you can just call the method as usual, e.g.

def show_version
  connect_to_database
  # ...
end

Or you could add the call to the constructor, to have it run first in every invocation:

def initialize(*args)
  super
  connecto_to_database
end

The call to super is very important, without it Thor will have no idea what to do.

Goof answered 11/11, 2010 at 9:26 Comment(3)
i want to write the call to "connect_to_database" only once. like you would write it in a regular class in the constructorDodson
Try adding a constructor: def initialize(*args); super; connecto_to_database; endGoof
I added that variant to my answer too.Goof
S
1

A rather under-documented feature of thor is the method default_task. Passed a symbol from within your thor script, you can set it to run a specific task and, using invoke, run other tasks.

For example:

default_task :connect_to_database
Sultry answered 23/2, 2011 at 15:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.