开发者

Rails: Where to put a variable needed across all controllers

I have a partial template that calls

feed = Feedzirra::Feed.fetch_and_parse("http://my.rss.feed")
@entries = feed.entries

This partial is called across about 80% of my site's pages - I'm just wondering about best practices re: where to store variables of t开发者_C百科his type. Any suggestions appreciated.


i guess use a filter - whichever applicable before or after.


You should put it in a before_filter of the application_controller. This way it will be assigned for every controller on every action.


This code should be placed in controller. The easiest way is to do it like this

class ApplicationController

  def fetch_feed_entries
    feed = Feedzirra::Feed.fetch_and_parse("http://my.rss.feed")
    @entries = feed.entries
  end

end

and then, inside any controller where this has to happen, you can write something like:

class PostsController

  before_filter :fetch_feed_entries

end

Now, this code will still fetch the feed for each request. If that is what you want, that is fine. But you could also keep the feed stored inside the session, so the feed is only fetched once per session. I am not sure if that makes sense for you.

Then you would write something like:

 def fetch_feed_entries
   session[:feed_entries] ||= Feedzirra::Feed.fetch_and_parse("http://my.rss.feed").entries
   @entries = session[:feed_entries]
 end

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜