Best way to organize non-controller logic?


#1

I don’t want to put certain code in my controller because I think it
makes things more confusing.

What is the best way to manage business logic such that it doesn’t end
up in the controller?

Basically, where should I put my regular utility classes and backing
objects that may not be models?

Thanks,
Wes


#2

application.rb can be a good spot for general purpose stuff - I put
e.g. my date formatting stuff in there to ensure dates are shown
consistently across an entire site.

Regards

Dave M.


#3

you could create modules and put them in the lib directory.


#4

Can you give an example of business logic that doesn’t interact with a
model?

On 3/20/06, Chris H. removed_email_address@domain.invalid wrote:

removed_email_address@domain.invalid


Jeremy H.
http://www.jeremyhuffman.com


#5

for me, I have to access external information on an AS/400 system. My
only
access to the system is via ODBC, for which there is no AR Adapter
avaliable.

so what i did was create a module for making connections to and
extracting
information from the AS/400 and put it in the lib directory.

AS400.rb

require ‘dbi’
module AS400
def AS400.get_some_data(args)
# do the AS/400 stuff here
# massage the data if needed (strip whitespaces, do some
calculations,
etc)
return data
end
end

then where i need it, typically a controller, i just require ‘AS400’ and
do
AS400.get_some_data(12345) .

Chris


#6

Personally, I’d say that looks like a model. You can just put it in
your models directory, and use it from controllers the way you
normally would. You’ll need to set up some mocks in order to unit
test it, since most back-end systems like that don’t provide usable
test regions. (At least not for the meaning of the word that OO
programmers are comfortable with.)

You can use the “model” and “service” controller class methods to make
sure it gets ‘required’ in the appropriate place.


#7

you could create modules and put them in the lib directory.

It’s cleaner BUT it’s cached in development mode => if you change it,
you need to restart the server.

Alain


#8

I have a filename that is an attribute of one of my model objects. It
references a file in the file system.

I need to figure out if that file is an Excel file, a CSV file, or
neither.

Wes

Jeremy H. wrote:

Can you give an example of business logic that doesn’t interact with a
model?

On 3/20/06, Chris H. removed_email_address@domain.invalid wrote:

removed_email_address@domain.invalid


Jeremy H.
http://www.jeremyhuffman.com


#9

class MyObject < ActiveRecord::Base

validates_each :filename do |fname|
unless [".xls", “.csv”].include?(fname.extname)
model.errors.add(fname, “File does not appear to be an excel or
csv
file”)
end
end