Ruby
metaprogramming

RubyのInstance Method定義、あるいはSend Methodの忘備録

class Example

  private

  def method_no_attr
    return 'call Example.method_no_attr'
  end

  def method_attr(attr)
    return "call Example.method_attr with attr = #{attr}"
  end

  def method_attrs(attr1, attr2)
    return "call Example.method_attrs with attr1 = #{attr1},  attr2 = #{attr2}"
  end

  def method_attrs_with_symbole(attr1:, attr2:)
    return "call Example.method_attrs_with_symbole with attr1 = #{attr1},  attr2 = #{attr2}"
  end

  def method_attrs_with_array_and_hash_option(attr1, *attr2, **attr3)
    return "call Example.method_attrs_with_array_and_hash_option with attr1 = #{attr1},  attr2 = #{attr2}, attr3 = #{attr3}"
  end
end

example = Example.new

example.send('method_no_attr')
# => "call Example.method_no_attr"

example.send('method_attr', 'Attr')
# => "call Example.method_attr with attr = Attr"

example.send('method_attrs', 'Attr1', 'Attr2')
# => "call Example.method_attrs with attr1 = Attr1,  attr2 = Attr2"

test_attr = ['TestAttr1', 'TestAttr2']
example.send('method_attrs', *test_attr)
# => "call Example.method_attrs with attr1 = TestAttr1,  attr2 = TestAttr2"

example.send('method_attrs_with_symbole', attr1: 'Attr1', attr2: 'Attr2')
# => "call Example.method_attrs_with_symbole with attr1 = Attr1,  attr2 = Attr2"

test_hash_attr = { attr1: 'TestHashAttr1', attr2: 'TestHashAttr2' }
example.send('method_attrs_with_symbole', test_hash_attr)
# => "call Example.method_attrs_with_symbole with attr1 = TestHashAttr1,  attr2 = TestHashAttr2"

example.send('method_attrs_with_array_and_hash_option', 'Attr1', 'Attr2', { attr3_1: 'Attr3_1' } )
# => "call Example.method_attrs_with_array_and_hash_option with attr1 = Attr1,  attr2 = [\"Attr2\"], attr3 = {:attr3_1=>\"Attr3_1\"}"

example.send('method_attrs_with_array_and_hash_option', 'Attr1', 'Attr2_1', 'Attr2_1', { attr3_1: 'Attr3_1' } )
# => "call Example.method_attrs_with_array_and_hash_option with attr1 = Attr1,  attr2 = [\"Attr2_1\", \"Attr2_1\"], attr3 = {:attr3_1=>\"Attr3_1\"}"


# OnlyRails(w/ ActiveSupport)

example_from_string_obj = 'Example'.constantize.new

example_from_string_obj.send('method_no_attr')
# => "call Example.method_no_attr"