How to access private class methods in Rails

767 views Asked by At

I have a class Initialization.

I have a method send_mail which is a class method

def self.send_mail
  a = user_stats
end

user_stats is a private method and when I try to call this method, it throws an error

class << self

  private

  def user_stats
    true
  end

end

When I tried accessing user_stats ,

 undefined method 'user_stats' for Initialization

Also tried

class << self

def self.send_mail
  a = user_stats
end

  private

  def user_stats
    true
  end

end
1

There are 1 answers

1
Marek Lipka On BEST ANSWER

Both of your approaches are correct, but in the latter you shouldn't use self, cause you already define method in Initialization's eigenclass:

class Initialization
  class << self
    def send_mail
      a = user_stats
    end
    private
    def user_stats
      true
    end
  end
end
Initialization.send_mail
# => true

Your first approach also works for me:

class Initialization
  def self.send_mail
    a = user_stats
  end
  class << self
    private
    def user_stats
      true
    end
  end
end
Initialization.send_mail
# => true