开发者

Ruby / Rails: determine how deeply nested an object is

I think this is a general ruby question, though in my case the objects involved are ActiveRecord models.

If I have a model that can be nested inside of another model, how can I determine how deeply nested the model is?

IE:

Model Root (Level 0)
- Model Level 1
- - Model Level 2
- - Model Level 2
- - Model Level 2
- - - Model Level 3
- - - Model Level 3
- Model Level 1
- Model Level 1

In let's say foo is a model nested three levels deep (as shown above). If I call foo.parent.parent.parent I would get the root model.

How could I define a method like: foo.depth that would return how many levels there are between foo and its root?

Thanks开发者_如何学Python!


Something like this should do the trick:

def depth
  parent.nil? ? 0 : 1+parent.depth
end


You need to create a recursive method. Something like:

class Sample

  attr_accessor :parent

  def depth

    # Base case.
    return 0 if parent.nil?

    # Recursive case.
    return parent.depth + 1

  end

end

This is assuming that your parent class will always respond to 'depth'. If not, you need to do some checks on respond_to?.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜