# Encapsulating multiple model logic and checking returns

**URL:** <https://www.ruby-forum.com/t/encapsulating-multiple-model-logic-and-checking-returns/135704>\
**Category:** Rails\
**Created:** [April 24, 2008, 11:29am UTC](https://www.ruby-forum.com/t/encapsulating-multiple-model-logic-and-checking-returns/135704 "2008-04-24T11:29:01Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jordelver](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@jordelver](https://www.ruby-forum.com/u/jordelver)\
**Post date:** [April 24, 2008, 11:29am UTC](https://www.ruby-forum.com/t/encapsulating-multiple-model-logic-and-checking-returns/135704/1 "2008-04-24T11:29:01Z")

</div>

Hi,  
I posted the other day, but I don’t think I was clear enough, this  
post tries to break down the essence of the problem 🙂

What is the best way to check what happened within a method call  
whilst still encapsulating the logic within the object. For example, I  
have an object method which calls upon other objects to get results  
back. Depending on the result of that call, different actions need to  
take place.

So, I have something like this:

class Cart  
has\_one :postage\_method

attr\_accessor :postage\_updated

def add(product)  
# do adding product  
calculate\_postage  
end

def remove(product)  
# do removal of product  
calculate\_postage  
end

private

```
def calculate_postage
  rate = postage_method.find_rate_for_weight(weight)
  if rate.some_condition
    # update db
    self.postage_updated = true
  else
    # update db
  end
end

```

end

class CartController  
before\_filter :get\_cart\_from\_db # into @cart

def add  
cart = @cart.add(product\_from\_params)  
if cart.postage\_updated  
# tell user postage was automatically updated  
else  
# do something else  
end  
end  
end

To me, the problem with this approach, is that you need to repeat  
these checks for every method where you are calling the method, which  
soon adds up and is not DRY. So:

class CartController  
before\_filter :get\_cart\_from\_db # into @cart

def add  
cart = @cart.add(product\_from\_params)  
if cart.postage\_updated  
# tell user postage was automatically updated  
else  
# do something else  
end  
end

def remove  
cart = @cart.remove(product\_from\_params)  
if cart.postage\_updated  
# tell user postage was automatically updated  
else  
# do something else  
end  
end

…etc

end

Also, what happens if I need to check multiple different conditions?  
Am I going about this in entirely the wrong way?

Many thanks for any advice.  
Cheers,  
Jordan
