Skip to content

Commit

Permalink
Restrict Task.named to only return Task classes (Shopify#349)
Browse files Browse the repository at this point in the history
  • Loading branch information
etiennebarrie authored and lawrencewong committed Apr 29, 2023
1 parent 5cefb47 commit f41503c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
9 changes: 6 additions & 3 deletions app/tasks/maintenance_tasks/task.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@ class << self
#
# @raise [NotFoundError] if a Task with the given name does not exist.
def named(name)
name.constantize
rescue NameError
raise NotFoundError.new("Task #{name} not found.", name)
task = name.safe_constantize
raise NotFoundError.new("Task #{name} not found.", name) unless task
unless task.is_a?(Class) && task < Task
raise NotFoundError.new("#{name} is not a Task.", name)
end
task
end

# Returns a list of concrete classes that inherit from the Task
Expand Down
8 changes: 8 additions & 0 deletions test/tasks/maintenance_tasks/task_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ class TaskTest < ActiveSupport::TestCase
assert_equal 'Maintenance::DoesNotExist', error.name
end

test ".named raises Not Found Error if the name doesn't refer to a Task" do
error = assert_raises(Task::NotFoundError) do
Task.named('Array')
end
assert_equal 'Array is not a Task.', error.message
assert_equal 'Array', error.name
end

test '.process calls #process' do
item = mock
Maintenance::TestTask.any_instance.expects(:process).with(item)
Expand Down

0 comments on commit f41503c

Please sign in to comment.