Ruby on rails -提取' .for() '到一个方法中



我有一个像这样的类:

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)。请不要在生产环境中使用它,除非你明白你在做什么。

最新更新