.

A Use for class << self |

A while ago I posted

class << self
  def find_all
    code_goes_here
  end  def destroy_all
    code_goes_here
  end
end

or you can write

def self.find_all
    code_goes_here
end
def self.destroy_all
    code_goes_here
end

I said that these two versions are functionally the same and that I ended up preferring the second form because it was easier to tell you are working on a class method. Turns out there is a difference.

Jay Fields answered this a while ago - but I just found it here

Basically if you use the first form - Ruby will honor your private/protected tags but in the second you would have to resort to something like this

class<<self;self;end.send :protected, :find_all :destroy_all

or


class << self
protected :find_all,:destroy_all
end

This isn’t the end of the world since I end up putting my private/protected stuff at the bottom of the file (Since that makes it easier to find out what is protected/private than sprinkling it into the code) but could be a gotcha if you didn’t know about the need for the extra code.

No Responses to 'A Use for class << self'

Leave a Reply

Moderation Active: Old stuff here... Therefore your comment on this post will be moderated (i.e. don't submit twice !)

    Categories
    Archives

    .