简体   繁体   中英

How come methods under 'private' and 'protected' can always be called in models (rails)?

I tested, that they, in fact, don't work:

class User < ActiveRecord::Base

  def self.call_protected_method
    protected_method
  end

  def self.call_private_method
    private_method
  end

  protected

  def self.protected_method
    puts "protected_method"
  end

  private

  def self.private_method
    puts "private_method"
  end

end

What i mean, by they don't work, is You can call all methods in this example. It doesn't matter if they are under private and/or protected.

# in rails console:
User.call_protected_method # => protected_method
User.protected_method      # => protected_method
User.call_private_method   # => private_method
User.private_method        # => private_method

Why is that? Whats the reason for ignoring 'private' and 'protected'?

UPDATE: my question isn't how to do this. My question is why doesn't this approach work in rails models!?

You are trying to define a private class method, and that would not work with that syntax. You want private_class_method

Have a look at these answers, too: Ruby class with static method calling a private method?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM