Rails 方式 - 命名空间 [英] The Rails Way - Namespaces

查看:18
本文介绍了Rails 方式 - 命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于如何做Rails 方式"的问题.对于具有面向公众和管理界面的应用程序,Rails 社区对如何做到这一点的普遍共识是什么?

I have a question about how to do something "The Rails Way". With an application that has a public facing side and an admin interface what is the general consensus in the Rails community on how to do it?

命名空间、子域还是完全放弃它们?

Namespaces, subdomains or forego them altogether?

推荐答案

实际上,管理界面没有真正的Rails 方式" - 您可以在许多应用程序中找到所有可能的解决方案.DHH 暗示他更喜欢命名空间(使用 HTTP 基本身份验证),但这仍然是一个简单的暗示,而不是官方的 Rails 意见之一.

There's no real "Rails way" for admin interfaces, actually - you can find every possible solution in a number of applications. DHH has implied that he prefers namespaces (with HTTP Basic authentication), but that has remained a simple implication and not one of the official Rails Opinions.

也就是说,我最近发现这种方法很成功(命名空间 + HTTP Basic).它看起来像这样:

That said, I've found good success with that approach lately (namespacing + HTTP Basic). It looks like this:

routes.rb:

map.namespace :admin do |admin|
  admin.resources :users
  admin.resources :posts
end

admin/users_controller.rb:

admin/users_controller.rb:

class Admin::UsersController < ApplicationController
  before_filter :admin_required
  # ...
end

应用程序.rb

class ApplicationController < ActionController::Base
  # ...

  protected
  def admin_required
    authenticate_or_request_with_http_basic do |user_name, password|
      user_name == 'admin' && password == 's3cr3t'
    end if RAILS_ENV == 'production' || params[:admin_http]
  end
end

authenticate_or_request_with_http_basic 的条件会在生产模式下或当您将 ?admin_http=true 附加到任何 URL 时触发 HTTP 基本身份验证,因此您可以在功能测试中对其进行测试并在您浏览开发站点时手动更新 URL.

The conditional on authenticate_or_request_with_http_basic triggers the HTTP Basic auth in production mode or when you append ?admin_http=true to any URL, so you can test it in your functional tests and by manually updating the URL as you browse your development site.

这篇关于Rails 方式 - 命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆