Skip to content

Instantly share code, notes, and snippets.

@siegy22
Last active August 29, 2015 14:27
Show Gist options
  • Save siegy22/30c8d2da2af80f08bb07 to your computer and use it in GitHub Desktop.
Save siegy22/30c8d2da2af80f08bb07 to your computer and use it in GitHub Desktop.
class MyAwesomeRake
class Task
attr_reader :dependencies, :description, :block
def initialize(description, dependencies = [], &block)
@dependencies = dependencies
@description = description
@block = block
end
def run(id)
@dependencies.each do |d|
possible_namespaces = possible_namespaces_for_id(id)
p possible_namespaces
possible_namespaces.each do |ns|
possible_task_id = ns << ":" << d
if MyAwesomeRake.task_exists?(possible_task_id)
MyAwesomeRake.run possible_task_id
break
end
raise Exception.new "Could not load dependency named '#{d}'\nDid research in following scopes: #{possible_namespaces.to_s}"
end
end
@block.call if @block
end
def possible_namespaces_for_id(id)
namespace = id.split(":")
namespace.pop
namespace = namespace.inject([]) { |memo, ns| memo << (memo + [ns]).join(":")}.reverse
namespace << "" # add empty string for default search
end
end
def self.run(identifier)
task = @tasks[identifier.to_s]
unless task == nil
task.run(identifier.to_s)
else
raise Exception.new("Could not find task named '#{identifier}'\nUse MyAwesomeRake.print_tasks to print all tasks")
end
end
def self.add_task(identifier, task)
@tasks ||= {}
@tasks[identifier.to_s] = task
end
def self.print_tasks
@tasks.map do |id, task|
puts "-- Task '#{id}' --\nDescription '#{task.description}'\nDependencies: #{task.dependencies}\n\n"
end
end
def self.task_exists?(identifier)
@tasks[identifier.to_s]
end
end
def namespace(name)
$namespace_stack ||= []
$namespace_stack.push(name)
$n = $namespace_stack.compact.join(":")
yield
$namespace_stack.pop
end
def task(identifier, &block)
if identifier.is_a?(Hash) # check for dependencies
id_with_namespace = [$n, identifier.keys.first].compact.join(":")
dependencies = identifier.values.first.is_a?(Array) ? identifier.values.first : [identifier.values.first]
dependencies = dependencies.map &:to_s
task = MyAwesomeRake::Task.new $d, dependencies, &block
MyAwesomeRake.add_task(id_with_namespace, task)
else
id_with_namespace = [$n, identifier].compact.join(":")
task = MyAwesomeRake::Task.new $d, &block
MyAwesomeRake.add_task(id_with_namespace, task)
end
$d = nil
end
def desc(description)
$d = description
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment