Ruby on rails 为Rails中的所有控制器创建全局变量

Ruby on rails 为Rails中的所有控制器创建全局变量,ruby-on-rails,ruby,Ruby On Rails,Ruby,我的所有控制器都有一个通用的基本URL。我想在一个地方将其声明为变量,并在所有控制器中使用它。这将使任何未来的更新快速和简单。可能吗?我在我所有的控制器中声明如下: @baseURL = "www.url.com/something/" 利用ruby的继承链。您可以在所有控制器的某个父类上将其定义为常量,通常为ApplicationController: class ApplicationController < ActionController::Base BASE_URL = "

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

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

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

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

然后它将对所有is子级可用,即应用程序控制器中的
PostsController

before_action :set_variables

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

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

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

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

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

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

  def self.baseURL
    @@baseURL
  end
end

class SomeFrontendController < ApplicationController

end
但是这太脏了更好使用常数:

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

class SomeFrontendController < ApplicationController

end

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

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

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

然而,通常在应用程序的其他部分需要更早或更晚的自定义URL(以及其他东西,如电子邮件地址),因此使用gem-like并将所有此类变量存储在一个位置(文件)来获得单一的真实来源是很有用的

class ApplicationController < ActionController::Base

  helper_method :base_url
  def base_url
    @base_url ||= "www.url.com/something/"
  end
end
class ApplicationController
我尽量避免设置变量前的操作。 在控制器和视图中,您可以调用
base\u url
方法


应用程序\u helper.rb

中包含此方法也是一样的,为什么不直接使用
根url
和相关(
链接到
url\u for
)?
class ApplicationController < ActionController::Base
  BASE_URL = "www.url.com/something/"
end

class SomeOtherController < ApplicationController
  def index
   @base_url = BASE_URL
  end
end
class ApplicationController < ActionController::Base

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