Let's say you have a config variable for facebook app id defined as:
TestSiteRails::Application.configure do
config.facebook_app_id = '123146123188122'
end
You want this variable to be available in every action, so that it's available in the main layout, application.html.haml:
!!! html
%html
%head
%body
#fb-root
:javascript
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '#{@facebook_app_id}', // Configured facebook app id
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File for x-domain communication
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
xfbml : true // parse XFBML tags on this page?
});
= yield :contents
Rather than repeating the code to do this in each controller action, how can I make this available to every action?
You could put it into your ApplicationController, so that all controllers inherit it:
class ApplicationController
before_filter :set_facebook_app_id
private
def set_facebook_app_id
@facebook_app_id ||= Rails.configuration.facebook_app_id
end
end
Or, if you need it to be accessible to views too, as a helper method:
class ApplicationController
def facebook_app_id
Rails.configuration.facebook_app_id
end
helper_method :facebook_app_id
end
您可以在application_controller中使用before_filter ,但我认为如果要使用它具有常量ID,则可以使用常量。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.