- Add
service_callerin your app'sGemfile.
# ruby version 2.7+, 3.0+ or later
gem 'service_caller', '~> 1.2.x'
# ruby version 2.6+ or eariler
gem 'service_caller', '~> 1.1.0'- Then, in your project directory, install the gem manually from your shell, run:
# Download and install
$ bundle installIf your project is already using an older version of service_caller, upgrade to the latest version with:
$ bundle update service_caller| Ruby Version | Rails Verision | Service Caller Version |
|---|---|---|
| 2.6 or eariler | 5.x | 1.1.0 |
| 2.7, 3.0+ or later | 6.x / 7.x / 8.x | 1.2.x |
- For ruby 2.6 or earlier (ruby 2.7 may show deprecated warning message)
class [Custom Service] < ServiceCaller
def initialize(*args)
...
@a = a
@b = b
end
def call
...
@result = "Your service result which you want to return"
end
end- For ruby 2.7 or ruby 3.0
class [Custom Service] < ServiceCaller
def initialize(*args, **hsh)
...
@a = a
@b = b
end
def call
...
@result = "Your service result which you want to return"
end
end- call the service (For ruby 2.6 or earlier)
service = [Custom Service].call(*args)- call the service (For ruby 2.7 or ruby 3.0)
service = [Custom Service].call(*args, **hsh)- Simply check if service is success or failed.
service.success? # success => true / failed => false
service.failed? # failed => true / success => false- Get success result information if service is success.
service.result- Get error information if service is failed.
service.errorclass CalBmi < ServiceCaller
def initialize(member_name, height: 1.55, weight: 52)
@member_name = member_name
@height = height
@weight = weight
end
def call
bmi = calculate_bmi
raise ServiceError.new(:member_name_not_found, error_msg: 'not enter the name') if @member_name.blank?
@result = "#{@member_name}'s BMI is #{bmi}"
end
private
def calculate_bmi
(@weight / @height**2).round(2)
end
end
# Call the BMI Service
body_insight = { height: 1.80, weight: 73 }
bmi = CalBmi.call('william', **body_insight)
bmi.success? # it will show the caller is success or failed
bmi.result # it will show you => william's BMI is 22.53
bmi = CalBmi.call('', **body_insight)
bmi.error # if failed, the service will raise the custom error => #<ServiceError: member_name_not_found>
bmi.error.key # :member_name_not_found
bmi.error.error_obj # {:error_msg=>"not enter the name"}