【发布时间】:2017-12-04 07:47:58
【问题描述】:
Rails 4.2
我为 User 模型创建了一个多步骤向导,即应用程序的访问者通过 4 步表单注册为 User。它在当前设置下工作。
但是,我不得不使用 require 语句来包含几个与向导相关的 ruby 文件。因此,Rails 不会自动加载这些文件。
我想重构相关文件,以便它们遵循 Rails 约定并能够自动加载。
当前结构 - 正在运行
app/wizards/user.rb 用户向导模型 - 在每个步骤上运行验证等
module Wizard
module User
STEPS = %w[step1 step2 step3 step4].freeze
# omitted class implementations, not relevant
class Base
end
class Step1 < Base
end
class Step2 < Step1
end
class Step3 < Step2
end
class Step4 < Step3
end
end
end
app/controllers/user_wizards_controller.rb
# I have to require the file above, would like to avoid
require Rails.root.join('app', 'wizards', 'user.rb')
class UserWizardsController < ApplicationController
# I have to specify the template, would like to avoid
def step1
render 'wizards/users/step1'
end
# Notice how I have to refer to module/classes above.
def wizard_user_for_step(step)
raise InvalidStep unless step.in?(::Wizard::User::STEPS)
"Wizard::User::#{step.camelize}".constantize.new(session[:user_attributes])
end
end
app/views/wizards/users/step1.html.erb
app/views/wizards/users/step2.html.erb
尝试的解决方案
autoload_paths 中的目录被认为是根目录,它们不反映命名空间。例如,app/models 下面的类不在 Models 命名空间下,任何命名空间都必须在该目录下。
例如,文件 app/services/doctor_finder.rb 不遵循自动加载约定,因为它定义了 Services::DoctorFinder 而不是 DoctorFinder。因此,该文件无法自动加载。
我要去……
模型
app/wizards/user/user.rb
app/wizards/user/base.rb
app/wizards/user/step1.rb
app/wizards/user/step2.rb
app/wizards/user/step3.rb
app/wizards/user/step4.rb
但是,我并没有走得太远。有什么想法吗?
【问题讨论】:
-
谢谢杰阿。这很有帮助。我已经取得了一些进展。如果有人需要解决方案,请询问,我会展示我的解决方案。
标签: ruby-on-rails ruby ruby-on-rails-4