0

I would like to declare a variable in my application_controller.rb controller that is accessible to all controllers that inherit from it. if possible I would like the variable only accessible in the child classes, nowhere else, including the views (unless specifically passed into the view).

I am new to Ruby and Rails and am unsure if the "protected" scope exists for variables, I have seen that it does for functions. I have not been able to find a simple answer and I have been experimenting a little in my app with different ways to declare variables and where they can be accessed. That has provided me with no information about how I can accomplish this.

Any help would be greatly appreciated.

Code:

class ApplicationController < ActionController::Base
    protect_from_forgery
    @admin_name = "AdminUserName"
    @admin_password = "AdminPassword"
end

class ProjectsController < ApplicationController
    http_basic_authenticate_with :name => @admin_name, :password => @admin_password, :except => [:index, :show]

    # controller functions here
end

This does not seem to be working for me.

4

1 回答 1

1

正如您所认识到的,ruby 中的变量不存在类似受保护范围的东西。您可以在 Rails 中使用实例变量来设置视图可访问的控制器中的变量。这是一个旧的 Rails 功能,您可以在视图中使用控制器中设置的实例变量

实例变量从一个实例继承到另一个实例

class A
  def make_ivar
    @foo = 'bar'
  end
end

class B < A
  def get_ivar
    @foo
  end
end

b = B.new
b.make_ivar
b.get_ivar #=> @foo

但请注意,通过将实例变量传递给视图 rails会破坏封装,并且通过所有部分使用它可能不是好的做法。最重要的是,一旦实例变量出现在视图中,就用局部变量替换它们

更新

在您的情况下,请使用constants。常量在定义它们的类的范围内并被继承,但它们对视图不可用,除非使用范围调用

class ApplicationController < ActionController::Base
  protect_from_forgery
  ADMIN_NAME = "AdminUserName"
  ADMIN_PW = "AdminPassword"
end

class ProjectsController < ApplicationController
  http_basic_authenticate_with :name => ADMIN_NAME, :password => ADMIN_PW, :except => [:index, :show]

  # controller functions here
end

我猜你不想在视图中调用它们。如果你真的想这样做,你可以这样做:

ApplicationController::ADMIN_NAME
于 2012-07-13T16:44:28.793 回答