Rails在lib /中为每个资产请求重新解析ruby文件

时间:2012-05-24 19:27:31

标签: ruby-on-rails asset-pipeline

Rails版本:3.1 Ruby版本:1.9.2

在我目前的一个项目中,我在每个请求的日志中收到了几十个“警告:已经初始化的常量”行。有问题的常量是在lib中定义的模块中。

我完全不知道为什么Rails每次请求解析此文件多达80次,直到我今天早上在开发模式中打开缓存(以测试其他内容)并注意到Rails报告了缓存未命中每一行。这是加载主页时约80个此类通知中的前4个:

/Users/evan/Development/Ruby/apps/thefriendex/lib/feeds_mixin.rb:2: warning: already initialized constant DEFAULT_LIMIT
cache: [GET /assets/application.css?body=1] miss
/Users/evan/Development/Ruby/apps/thefriendex/lib/feeds_mixin.rb:2: warning: already     initialized constant DEFAULT_LIMIT
cache: [GET /assets/_have_need_bar.css?body=1] miss
/Users/evan/Development/Ruby/apps/thefriendex/lib/feeds_mixin.rb:2: warning: already initialized constant DEFAULT_LIMIT
cache: [GET /assets/admin.css?body=1] miss
/Users/evan/Development/Ruby/apps/thefriendex/lib/feeds_mixin.rb:2: warning: already     initialized constant DEFAULT_LIMIT
cache: [GET /assets/blurb_ad.css?body=1] miss

所以看起来它再次为每个资产请求重新解析lib / feeds_mixin.rb。我曾经有一个配置行将lib / * .rb添加到自动加载路径,但我删除它没有效果。

有问题的模块只是一个简单的模块,有一个常量和三个实例方法。它通过简单的包含混合到两个控制器中,如果需要,我可以添加该代码。

有关为何每次请求资产时都会重新解析此文件的问题?

代码:mixin(lib / feeds_mixin.rb)

module FeedsMixin
  DEFAULT_LIMIT = 6

  def friends_feed_items(opts = {})
     # do stuff
  end

  def friends_of_friends_feed_items(opts = {})
     # do stuff
  end

  def community_feed_items(opts = {})
    # do stuff
  end

  def build_feed_hash(type, items, opts) 
    # do stuff
  end
end

代码:它包含在哪里(lib / controllers / dashboard_controller.rb) (另一个控制器与此非常相似)

require 'feeds_mixin'
class DashboardController < ApplicationController

  extend ActiveSupport::Memoizable
  include FeedsMixin
  layout 'dashboard'
  before_filter :require_user, :set_feeds

  LIMIT = 6
  DEFAULT_DATE_THRESHHOLD = 14.days

  def index
  end

  def set_feeds
    @friends_feed = friends_feed_items(:since => since_date, :limit => LIMIT)
    @friends_of_friends_feed = friends_of_friends_feed_items(:since => since_date, :limit => LIMIT)
    @community_feed = community_feed_items(:since => since_date, :limit => LIMIT)
  end

  def since_date
    DEFAULT_DATE_THRESHHOLD.ago
  end
  memoize :since_date
end

0 个答案:

没有答案