10
7

More than 5 years have passed since last update.

rails consoleでprivate methodを呼ぶ

Last updated at Posted at 2016-01-25

結論から言うと、、

Object#sendを使いましょー!

つまり、sendはprotectedなメソッドもprivateなメソッドも呼び出せます。
http://ref.xaio.jp/ruby/classes/object/send

ちょっとした説明。

class Sample
  def foo
    'this is public method'
  end

  private
  def bar
    'this is private method'
  end
end

こんなメソッドをコンソールで試したい時、

[1] pry(main)> Sample.new.foo
"this is public method"

[2] pry(main)> Sample.new.bar
private method `bar' called for #<Sample:0x007fc166e6ba48>

エラーになります。

そんな時は、

[3] pry(main)> Sample.new.send(:bar)
"this is private method"

こうすれば呼び出せます。

10
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
7