views:

186

answers:

2

So I have a model that I need to be able to serialize to/read from an Excel(XLS) document. I am a bit of a loss as to where this code actually belongs. My initial thought is that the to_xls is a view, but after poking around and seeing things like (to|from)_xml and (to|from)_json in ActiveRecord, I was wondering if maybe this stuff belonged in the model. Alternatively, does it belong in just a whole separate container somewhere?

For what it's worth, users will be downloading models from the site, modifying them in excel, then posting them.

A: 

to_xls should definitely be a view. I'd try a /app/views/foos/show.xls.erb, but if you don't like ERB for XLS views, try the RbTemplateHandler to do rendering in pure Ruby.

from_xls is a different beast altogether. It certainly doesn't belong in a controller. It logically belongs in the model, but I'd extract it to a mixin. If you're only pulling in XLS for one model, then the following setup should suffice:

# app/models/foo.rb
class Foo
  extend XLS2Foo
  ...
end

# lib/foo_from_xls
module XLS2Foo
  def to_foo(xls)
    ...
  end
end

If you need to do it for a bunch of models, you might try a parser-generator DSL in you lib directory and declare yourself parsers for each model in the model classes.

James A. Rosen
Realized that I need to do the same thing for a couple models, basically serializing to a tree-table. The main issue is whether I declare it as a model mix-in, or as something that acts on models that are a certain structure.
Joe Arasin
A: 

to/from_xls are not supported by Rails. There is a plugin, but I haven't used it to_xls plugin for Rails. A better way might be for you to go to and from a CSV using FasterCSV and get something that is usable. Here is one example: Export to_csv from ActiveRecord

Thanatos
I have functions written to do what I want to do. I'm trying to focus on where I should put the code.
Joe Arasin