Rails MVC – Controllers vs Models for File Manipulation

mvcruby-on-rails

This post by Jamis Buck about keeping Rails controllers skinny has always stuck with me. I have an app in which a zip file consisting of an XML file and some images is uploaded and used to create the model (mostly from the xml file, which points to the images).

Should all the code dealing with extracting the files from the zip and moving them to their appropriate place go in the controller or the model?

thanks!

Best Answer

That article is pretty much classic. Yes, you should stick to the "fat models, skinny controllers, stupid views" architecture as long as the models make sense as objects (and they almost always do).

In your case, I'm not really sure what the output "model" should look like, but let's say it's a gallery. So you can create a model like this:

class Gallery # no "< ActiveRecord" if don't work with database

  attr_accessor :zip_file_path, :xml, :images

  def initialize(params ={})
    @zip_file_path = params[:zip_file_path]
    @xml = nil
    @images = []
    @output = nil # model: html code, path to file...
  end

  def generate_model
    unzip_file! # populates @xml and @images
    transform_xml! # creates model into @output
    @output
  end

  def unzip_file!
    ...
  end

  def transform_xml!
    ...
  end

end

It's just a rough design, you might want to make it more function-oriented (@xml, @images = unzip_file(@zip_file_path) ) etc.

Controller will then act just as a mediator between model and views/user:

class GalleriesController < ApplicationController
  def new()
    # display upload form for zip_file
  end

 def create()
   # check input here, or leave it to model validations

  @output = Gallery.new(params).generate_model
 end

end