Ruby on Rails:是否可以扩展方法而不覆盖它?

时间:2010-07-09 15:28:33

标签: ruby-on-rails

我想更改create方法的重定向,但我不想覆盖整个方法。

就像默认情况下,如果create(比方说)存在,它将具有类似

的内容
  respond_to do |format|
      if @user.save(params[:user])
        flash[:notice] = 'The user has been updated'
        format.html { redirect_to :controller => "subscriptions",
                                  :action => "show",
                                  :id => @user.account_id }
        format.xml { head :ok }
      else
        format.html { render :action => :edit }
            format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
        end
    end

或类似的......

但是它说的是format.html ... 我希望能够在我的类中更改继承此方法的redirect_to ...但我不想重写整个事情。 = \

想法?

2 个答案:

答案 0 :(得分:1)

调用super不会解决您的问题,因为您想要更改方法的内部工作方式,而不是传递新参数或向其添加代码。

我要做的是创建具有通用功能的第三个函数(让我们称之为common_routine)。然后,您将从需要访问它的两个地方调用common_routine。但是,要根据需要更改代码,您将传递一个块,并在方法中生成该块以修改方法的工作方式。

示例:

def common_routine
  respond_to do |format|
    if @user.save(params[:user])
      flash[:notice] = 'The user has been updated'
      format.html { yield }
      format.xml { head :ok }
    else
      format.html { render :action => :edit }
      format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
    end
  end
end

然后你用:

来称呼它
common_routine { redirect_to :controller => "subscriptions", :action => "show", :id => @user.account_id }

common_routine { redirect_to root_path }

您传递给common_routine的代码块将被“生成”,这使您可以根据需要进行相同的功能并进行微调。

答案 1 :(得分:0)

如果你知道原始方法采用什么参数,你可以调用super方法。

class Foo
  def foo(arg)
    arg*2
  end
end

class Bar < Foo
  def foo(arg)
    super(arg) + 3
  end
end

a = new Foo
a.foo(2)     # => 4
b = new Bar
b.foo(2)     # => 7
相关问题