Errors treatment in a non ActiveRecord class

Hi everyone! Are you ok? I hope yes…

I’m working on a class whose its responsibility is calculate Brazilian taxes.

Its use is so and so like this:

invoice_product = InvoiceProduct.new(filtered_params)

operationkind = Operationkind.find(params[:operationkind_id])

recipient = Person.find(params[:recipient_id])

finder = Taxes::Premisefinder.new

finder.find(

current_user.licenciated,

recipient.city.uf,

operationkind,

invoice_product.product.taxgroup,

invoice_product)

render json: invoice_product, status: :created

``

It’s used in a controller to respond as json in a rest API. It’s not a ActiveRecord descendent class.

My doubt is: what is the best way to collect the possible errors generated from Taxes::Premisefinder?

Should I do Taxes::Premisefinder generates exceptions and catch them on the controller?

Should I use similar strategy of ActiveRecord using Errrors class?

In this case, what’s the Rails way to work?

Thanks!

Hi Anjos,

Which is the class that is not ActiveRecord descendent ? Im assuming Taxes::Premisefinder

define an errors class this way

class Error

attr_accessor :errors

def initialize

@errors = {}

end

def add(key, message)

self.errors[key] = message

end

end

class Car

def errors

@errors ||= Error.new

end

end

@car = Car.new

@car.errors.add(:name, “Invalid”)

And you can define valid? method and add errors accordingly.

Its not perfect but can be a good starting point.

Thanks for your reply!

I did this and now it’s perfect.

513.gif Merry Xmas

image001.jpg