Skip to content

Commit

Permalink
API: added error class
Browse files Browse the repository at this point in the history
It can be used when lookup fails.

## Usage

```ruby
scope_class = Scope.for(object.class) or
  raise Magic::Lookup::Error.for(object, Scope)
```
  • Loading branch information
Alexander-Senko committed Oct 10, 2024
1 parent 275cfb3 commit 4df261a
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/magic/lookup.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

module Magic
module Lookup
autoload :Error, 'magic/lookup/error'

include Memery

memoize def for object_class
Expand Down
14 changes: 14 additions & 0 deletions lib/magic/lookup/error.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# frozen_string_literal: true

module Magic
module Lookup
class Error < NameError
def self.for object, lookup_class
default_name = lookup_class.name_for object.class

new "no #{lookup_class} found for #{object.class}, default name is #{default_name}",
default_name, receiver: object
end
end
end
end
7 changes: 7 additions & 0 deletions sig/magic/lookup/error.rbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module Magic
module Lookup
class Error < NameError
def self.for: (any) -> Error
end
end
end
30 changes: 30 additions & 0 deletions spec/magic/lookup/error_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# frozen_string_literal: true

class Scope
extend Magic::Lookup

def self.name_for(object_class) = "#{object_class}Scope"
end

module Magic
module Lookup
RSpec.describe Error do
subject { described_class.new }

describe '.for', :method do
its([[], Scope]) do
is_expected.to be_instance_of described_class
end

its([[], Scope]) do
is_expected.to be_a StandardError
end

its([[], Scope]) do
is_expected.to have_attributes to_s: /no Scope found/,
name: 'ArrayScope', receiver: []
end
end
end
end
end

0 comments on commit 4df261a

Please sign in to comment.