undefined Ruby中的类方法(在方法定义之前调用)

时间:2017-03-30 21:05:25

标签: ruby-on-rails ruby mongoid class-method bit-fields

我最后遇到了一个非常奇怪的错误:

当我运行此代码时:

class HomeFeature
    include Mongoid::Document
    include Mongoid::Timestamps
    include Mongoid::Bitfield

    belongs_to :home

    def self.amenities
        %w(lobby jacuzzi sauna cinema games roof_garden events_room tennis_court visits_space roaster green_areas cistern)
    end

    bitfield :amenities, *HomeFeature.amenities.map(&:to_sym)
end

它完美无缺,但是这个:

class HomeFeature
    include Mongoid::Document
    include Mongoid::Timestamps
    include Mongoid::Bitfield

    belongs_to :home

    bitfield :amenities, *HomeFeature.amenities.map(&:to_sym)

    def self.amenities
        %w(lobby jacuzzi sauna cinema games roof_garden events_room tennis_court visits_space roaster green_areas cistern)
    end
end

给我错误: ```NoMethodError:未定义的方法`设施' for HomeFeature:Class````

有人可以解释为什么会这样吗?非常感谢

1 个答案:

答案 0 :(得分:1)

在第二个示例中,您尝试在定义类方法amenities之前调用它(它在行*HomeFeature.amenities.map(&:to_sym)上调用,但仅在稍后定义)。源代码的排序非常重要,因为代码是从上到下解析的。