通过调用super来覆盖方法

时间:2014-06-25 19:10:11

标签: ruby

我有两个文件a.rbb.rb

a.rb有:

class Work

def create type, id, clean = false, implant = false, sizes
  if clean
    # Do this.
  end   
  if implant
    # Do that.  
  end
end

b.rb有:

class BlogWork<Work

def run
  @blog[:save] = create 'test', @blog[:id], true, true, img_sizes
end

有没有办法在super上致电b.rb,以便我无需在主implant=false {{sizes {{}}上引用a.rbcreate 1}}功能但仍传递implantimg_sizes值?

2 个答案:

答案 0 :(得分:1)

如果要保持create方法在参数方面的通用性,可以在末尾添加可选的哈希参数:

def create(type, id, sizes, options = {})
  if options[:clean]
    # Do this.
  end   
  if options[:implant]
    # Do that.  
  end
end

def run
  @blog[:save] = create 'test', @blog[:id], img_sizes , clean: true, implant: true
end

如果您使用ruby 2.0及更高版本,并且事先知道所需参数列表,则可以使用命名参数:

def create type, id, sizes, clean: false, implant: false
  if clean
    # Do this.
  end   
  if implant
    # Do that.  
  end
end

def run
  @blog[:save] = create 'test', @blog[:id], img_sizes , clean: true, implant: true
end

答案 1 :(得分:0)

在班级BlogWork中

def create type, id, clean = false, implant = true, sizes
    super(type, id, clean)

    if implant
      # Do that.  
    end
end

IN a.rb

def create(type, id, sizes)
   if options[:clean]
     # Do this.
   end   
end