Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ class ExampleService < ApplicationService
end
end
```
You can also override context base class like this
```ruby
context base_class: 'ApplicationContext' do
end
```

Next you use it as follows:
```ruby
Expand Down
22 changes: 6 additions & 16 deletions lib/servitium/service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -268,39 +268,29 @@ def context_class_name
name.gsub("Service", "Context")
end

def context_class!
def context_class!(*args)
return context_class if context_class

context_class_parts = context_class_name.split("::")
context_class_name_part = context_class_parts.pop
context_module_name = context_class_parts.join("::")
context_module = context_module_name.present? ? context_module_name.constantize : Object

context_base_class_name = args.first[:base_class] if args.first&.key?(:base_class)
context_base_class_name ||= superclass.to_s.gsub("Service", "Context")
context_base_class_name ||= "Servitium::Context"
context_module.const_set(context_class_name_part, Class.new(context_base_class_name.constantize))
context_class
end

# Get the base class for new contexts defined using context blocks
# Defaults to Servitium::Context
def context_base_class_name
@@_context_base_class_name ||= "Servitium::Context"
end

# Override the base class for contexts defined using context blocks, you can use this to
# change the base class to your own ApplicationContext
def context_base_class_name=(base_class)
@@_context_base_class_name = base_class
end

def context(*, &)
return initialized_context(*) unless block_given?

begin
context_class!.new
context_class!(*).new
rescue
nil
end
context_class!.class_eval(&)
context_class!(*).class_eval(&)
end

def initialized_context(*)
Expand Down