LoginSignup
0
0

More than 5 years have passed since last update.

ruby モジュールに定義する処理で、

Posted at

モジュール内の定義する処理の実装方法で、

外から呼び出せる可視性みたいなのを制御したい場合には、どうするのがいいんすかね?

下記1~5の実装方式では、それぞれスコープも違うし使用目的も違ってくるんですが、
なんか一般的なガイドラインみたいなのとかってあるんすかね?

という質問です

m.rb
# モジュールに定義する処理で、
module M
  # ■ 1. (たぶん簡単に)外から呼べない - クラスインスタンス変数のラムダ
  @class_var_proc = -> arg do
    puts "  @class_var_proc: #{arg}"
  end

  # ■ 2. (たぶん簡単に)外から呼べない - クラスインスタンスのprivateメソッド
  class << self
    private
    def private_method(arg)
      puts "  private_method: #{arg}"
    end
  end

  # 〇 3. 外から呼べる - 定数のラムダ
  CONST_PROC = -> arg do
    puts "CONST_PROC: #{arg}"
    private_method(arg)   # 中から呼ぶ
    @class_var_proc[arg]  # 中から呼ぶ
    puts '----------'
  end

  # 〇 4. 外から呼べる - クラスメソッド
  def self.class_method(arg)
    puts "class_method: #{arg}"
    private_method(arg)   # 中から呼ぶ
    @class_var_proc[arg]  # 中から呼ぶ
    puts '----------'
  end

  # 〇 5. 外から呼べる - モジュールファンクション
  module_function
  def module_function_method(arg)
    puts "module_function_method: #{arg}"
    private_method(arg)   # 中から呼ぶ
    @class_var_proc[arg]  # 中から呼ぶ
    puts '----------'
  end
end

if __FILE__ == $0
  M::CONST_PROC[1] # 外から呼ぶ

  M.class_method(2) # 外から呼ぶ

  M.module_function_method(3) # 外から呼ぶ
end

↑の出力結果

CONST_PROC: 1
  private_method: 1
  @class_var_proc: 1
----------
class_method: 2
  private_method: 2
  @class_var_proc: 2
----------
module_function_method: 3
  private_method: 3
  @class_var_proc: 3
----------
0
0
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
0
0