为Rails中的所有控制器创建一个全局变量

时间:2016-01-27 18:18:46

标签: ruby-on-rails ruby

我的所有控制器都有一个通用的基本URL。我想在一个地方将它声明为一个变量,并在我的所有控制器中使用它。这将使任何未来的更新变得快速而简单。那可能吗?我在我的所有控制器中都这样声明:

@baseURL = "www.url.com/something/"

6 个答案:

答案 0 :(得分:4)

利用ruby的继承链。您可以将所有控制器的某个父类定义为常量,通常为ApplicationController

class ApplicationController < ActionController::Base
  BASE_URL = "www.url.com/something/"
end

然后它将对所有孩子都可用,即PostsController < ApplicationController

答案 1 :(得分:4)

在您的应用程序控制器中。

before_action :set_variables

def set_variables
 @baseURL = "www.url.com/something/"
end

当您使所有控制器继承ApplicationController时,可以在所有操作和视图中访问此@baseURL实例变量。

答案 2 :(得分:1)

您可以在ApplicationController中定义一个方法,并像使用helper_method一样使用该方法从视图中访问它。

class ApplicationController < ActionController::Base

  helper_method :base_url
  def base_url
    @base_url ||= "www.url.com/something/"
  end
end

我尽量避免before_actions设置变量。 在您的控制器和视图中,您可以调用base_url方法。

将此方法包含在application_helper.rb

中也是一样的

答案 3 :(得分:0)

Rails控制器继承自ApplicationController。试着把它放在那里:

def baseUrl
 @baseURL = "www.url.com/something/"
end

答案 4 :(得分:0)

您可以在应用程序控制器中定义一个类变量:

class ApplicationController < ActionController::Base
  @@baseURL = "www.url.com/something/"

  def self.baseURL
    @@baseURL
  end
end

class SomeFrontendController < ApplicationController

end

现在您可以在所有控制器中访问@@ baseURL或调用类方法:

SomeFrontendController.baseURL
# => "www.url.com/something/"

这很脏。 更好使用常量:

class ApplicationController < ActionController::Base
  BASE_URL = "www.url.com/something/"
end

class SomeFrontendController < ApplicationController

end

现在,您可以访问BASE_URL或:

SomeFrontendController::BASE_URL

答案 5 :(得分:0)

如果它只是一个变量并且您确定,那么仅在控制器范围内需要它,在ApplicationController中声明一个常量应该足够了:

class ApplicationController < ActionController::Base
  BASE_URL = "www.url.com/something/"
end

class SomeOtherController < ApplicationController
  def index
   @base_url = BASE_URL
  end
end

然而,在应用程序的其他部分通常需要更早或更晚的自定义URL(以及电子邮件地址等其他内容),因此通过使用像https://github.com/settingslogic/settingslogic这样的gem来存储所有这些内容,这对于获得单一的事实来源非常有用。变量在一个地方(文件)。

相关问题