Я думаю, что вы могли бы поместить большую часть этой логики в вашу модель ProjectFile
или любое другое подходящее название модели:
ProjectFile < ActiveRecord::Base
def node_list(project_id, folder_id, user_id)
node_list = []
# If no project id was specified, return a list of all projects.
if project_id == nil and folder_id == nil
# Get a list of projects for the current user.
projects = Project.find_all_by_user_id(user_id)
# Add each project to the node list.
projects.each do |project|
node_list << {
:text => project.name,
:leaf => false,
:id => project.id.to_s + '|0',
:cls => 'project',
:draggable => false
}
end
else
# If a project id was specfied, but no file id was also specified, return a
# list of all top-level folders for the given project.
if project_id != nil and folder_id == nil
# Look for top-level folders for the project.
folder_id = 0
end
directory_list = []
file_list = []
known_file_extensions = ['rb', 'erb', 'rhtml', 'php', 'py', 'css', 'html', 'txt', 'js', 'bmp', 'gif', 'h', 'jpg', 'mov', 'mp3', 'pdf', 'png', 'psd', 'svg', 'wav', 'xsl']
# Get a list of files by project and parent directory.
project_files = ProjectFile.find_all_by_project_id(project_id,
:conditions => "ancestry like '%#{folder_id}'",
:order => 'name')
project_files.each do |project_file|
file_extension = File.extname(project_file.name).gsub('.', '')
if known_file_extensions.include? file_extension
css_class_name = file_extension
else
css_class_name = 'unknown'
end
# Determine whether this is a file or directory.
if project_file.is_directory
directory_list << {
:text => project_file.name,
:leaf => false,
:id => project_id + '|' + project_file.id.to_s,
:cls => css_class_name
}
else
file_list << {
:text => project_file.name,
:leaf => true,
:id => project_id + '|' + project_file.id.to_s,
:cls => css_class_name
}
end
end
node_list = directory_list | file_list
end
end
Затем разбить node_list
на более управляемые методы.Метод, который я определил выше, является длинным и делает несколько вещей (низкая когезия), поэтому его разбивка поможет бороться с этими недостатками.
В вашем контроллере вы бы назвали это следующим образом:
class ProjectFileController < ApplicationController
before_filter :require_user
def list
@project_id = params[:project_id]
@folder_id = params[:folder_id]
current_user = UserSession.find
@user_id = current_user && current_user.record.id
nodes = node_list(@project_id, @folder_id, @user_id)
render :json => nodes
end
end
Теперь ваш контроллер намного проще для чтения, и бизнес-логика извлечена.Это следует за мантрой «Тощие контроллеры, толстые модели».