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:
- Ruby coding conventions suggests to use a 2-spaces indentation, not 4-spaces
- Do not put a space between method name and arguments
- Do not use explicit receiver (
self.
) to call an instance method - Do not use explicit return
精彩评论