【问题标题】:Rails 4.2 naming conventions for a multi-step wizardRails 4.2 多步骤向导的命名约定
【发布时间】: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

尝试的解决方案

基于此statement by xfn

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

但是,我并没有走得太远。有什么想法吗?

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/18934115/…
  • 谢谢杰阿。这很有帮助。我已经取得了一些进展。如果有人需要解决方案,请询问,我会展示我的解决方案。

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

如果您想自动加载这些文件,请将其移动到例如服务或步骤目录中,例如:

 app/services/wizards/user/step1 

并且rails应该自动加载模块:

 module Wizards::User
    class Step1
    end
 end

取决于 Rails 版本,您需要将“服务”添加到自动加载路径。

关于意见:

 render 'wizards/users/step1'

还不错,在我看来可以被认为是一种很好的做法。(使用渲染方法允许您将非全局变量传递给查看)

如果你想删除这一行,你应该把 UserWizardsController 的视图放到 user_wizards/step1.html.xxx 中

或者如果你想在wizards/users/step1.html.xxx中查看 您应该以这种方式确定您的控制器范围:

module Wizards
  class UsersController < ApplicationController
  end
edn

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-01
    相关资源
    最近更新 更多