开发者

Class-wide constant

i need to implement < and > operators for a Model.

The code is like this:

class Product < ActiveRecord::Base
    sizes_map = ["s", "m", "l", "xl", "xxl"]

    def < (rhs)
        return sizes_map.index(self.size_label) < sizes_map.index(rhs.size_label)
    end
end

When i do:

pl = Product.new :size_label => "s"
pr = Product.new :size_label => "l"
pl 开发者_JAVA技巧< pr

I get following error:

NameError: undefined local variable or method `sizes_map'

It turns out, that class-wide constant is not visible in it's method.

Also, Product:sizes_map raises the same error.

What's wrong here ?


sizes_map should be a constant if you want to default it in the class in that way. Constants are defined upper case.

class Product < ActiveRecord::Base
  SIZES = ["s", "m", "l", "xl", "xxl"]

  def <(rhs)
    SIZES.index(size_label) < SIZES.index(rhs.size_label)
  end
end

Some additional suggestion:

  1. Ruby coding conventions suggests to use a 2-spaces indentation, not 4-spaces
  2. Do not put a space between method name and arguments
  3. Do not use explicit receiver (self.) to call an instance method
  4. Do not use explicit return
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜