将 .for() 提取到方法中
extract `.for()` into a method
我有一个像这样的class:
class House
def bricks
Brick.for(@house_plan).where(size: 5)
end
def wood
Wood.for(@house_plan).where(size: 5)
end
end
我的目标是提取调用 for(self).where(size: 5)
:
我首先尝试的是:
class House
def bricks
Brick.match_material
end
def wood
Wood.match_material
end
def match_material
for(@house_plan).where(size: 5)
end
end
但是我得到了这个错误:
syntax error, unexpected '\n', expecting :: or '[' or '.'
然后我把代码改成:
def match_material
.for(@house_plan).where(size: 5)
end
现在当我这样做时:
house = House.new(HousePlan.new)
house.bricks
我得到这个错误:
formal argument cannot be an instance variable
这一行:for(@house_plan).where(size: 5)
我做错了什么?
你的方法不对,记住 match_material
方法总是在你自己的上下文中被调用。我会这样做:
def bricks
match_material(Brick)
end
def wood
match_material(Wood)
end
def match_material(klass)
klass.for(@house_plan).where(size: 5)
end
出于好奇:
def bricks
klazz = Kernel.const_get(__callee__[0...-1].capitalize)
klazz.for(@house_plan).where(size: 5)
end
alias :woods :bricks
注意:在这种方法中,别名方法的命名要一致(bricks
,woods
。)请不要在生产中使用它,除非您了解自己在做什么。
我有一个像这样的class:
class House
def bricks
Brick.for(@house_plan).where(size: 5)
end
def wood
Wood.for(@house_plan).where(size: 5)
end
end
我的目标是提取调用 for(self).where(size: 5)
:
我首先尝试的是:
class House
def bricks
Brick.match_material
end
def wood
Wood.match_material
end
def match_material
for(@house_plan).where(size: 5)
end
end
但是我得到了这个错误:
syntax error, unexpected '\n', expecting :: or '[' or '.'
然后我把代码改成:
def match_material
.for(@house_plan).where(size: 5)
end
现在当我这样做时:
house = House.new(HousePlan.new)
house.bricks
我得到这个错误:
formal argument cannot be an instance variable
这一行:for(@house_plan).where(size: 5)
我做错了什么?
你的方法不对,记住 match_material
方法总是在你自己的上下文中被调用。我会这样做:
def bricks
match_material(Brick)
end
def wood
match_material(Wood)
end
def match_material(klass)
klass.for(@house_plan).where(size: 5)
end
出于好奇:
def bricks
klazz = Kernel.const_get(__callee__[0...-1].capitalize)
klazz.for(@house_plan).where(size: 5)
end
alias :woods :bricks
注意:在这种方法中,别名方法的命名要一致(bricks
,woods
。)请不要在生产中使用它,除非您了解自己在做什么。