开发者

Override ActionDispatch::Request method

I am trying to get my head around the concept of object orientation and inheritance in Rails coming from a procedural background, and particularly I want to understand how I would override default behaviour in classes in the Rails framework.

Say for example I wanted to override a method in ActionDispatch::Request, I assume I do something like this:

Request < ActionDispatch::Request

 def method_i_want_to_override
  a开发者_如何学运维ctions_to_perform
 end

end

I am confused though how I load this in order for it to change the way the ActionDispatch::Request object behaves.


When you override a method by using inheritance (i.e. you're inside a subclass), you can just declare the method again, like you have done:

def method_that_exists_in_superclass
  # stuff here
end

Now, often you don't want to re-implement the entire method behaviour, you just want to do something additional to what it already does (or undo something it does). In this case you use super to call the original method:

def method_that_exists_in_superclass
  result = super
  result + 7 # for example... but use your imagination
end

You can also pass arguments to super, as you'd expect, which means you can override arguments by hard-coding one of your own:

def method_that_exists_in_superclass(arg1, arg2)
  super(arg1, :foo)
end

If you call super without any arguments, all of the arguments from the subclass' method are passed along to the parent. This includes any block that was given.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜