Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Method Wrapper

Method Wrapper

Introduction to ruby method wrappers

maimai77

June 21, 2016
Tweet

Other Decks in Programming

Transcript

  1. Method Wrappers 4 Around Alias 4 Module#alias_method 4 Prepend Wrapper

    4 Module#prepend ( ruby >= 2.0 ) 4 Refinements Wrapper 4 Module#refine ( ruby >= 2.0 but darkpowered)
  2. Module#alias_method class MyClass def my_method 'my_method' end alias_method :m, :my_method

    end obj = MyClass.new obj.my_method #=> "my_method" obj.m #=> "my_method"
  3. Module#alias_method ྫ: String#rjust '123'.rjust(5) #=> " 123" '123'.rjust(5, '0') #=>

    "00123" શͯͷݺͼग़͠ݩͰୈ2Ҿ਺ͷσϑΥϧτ஋Λ'0'ʹ͍ͨ͠
  4. Module#alias_method class String def rjust_with_zero(integer, padstr=' ') padstr = '0'

    if padstr == ' ' rjust_without_zero(integer, padstr) end alias_method :rjust_without_zero, :rjust alias_method :rjust, :rjust_with_zero end '123'.rjust(5) #=> "00123"
  5. But, on Rails5... def alias_method_chain(target, feature) ActiveSupport::Deprecation.warn( "alias_method_chain is deprecated.\

    Please, use Module#prepend instead.\ From module, you can access the originalmethod using super." ) ... end
  6. Module#prepend ܧঝνΣʔϯͰincluderͷલʹૠೖ͞ΕΔ (લఏ஌ࣝ: ϝιου୳ࡧɺܧঝνΣʔϯ) module M end String.include M String.ancestors

    #=> [String, M, Comparable, Object, Kernel, BasicObject] String.prepend M String.ancestors #=> [M, String, Comparable, Object, Kernel, BasicObject]
  7. Module#prepend module RjustWithZero def rjust(integer, padstr=' ') padstr = '0'

    if padstr == ' ' super end end String.prepend RjustWithZero '123'.rjust(5) #=> "00123"
  8. Good and Bad Parts of Module#alias_method good - ϝιουͷఆ͕ٛຊདྷͷϝιουͱಉ͡৔ॴʹͳΔͷͰΘ͔Γ΍͍͢ʢʁʣ -

    Ruby1.9Ҏલͷݪ࢝࣌୅ʹ͓͍ͯ͸΄΅།Ұͷखஈ bad - هड़͕൥ࡶ - _with_ϝιουͷఆٛͱalias_methodݺͼग़͠͸ͲΕ͚ͩ཭Ε͍ͯͯ΋ྑ͍ʢϧʔϧ͕ඞཁʣ - ඞવతʹ3୯ޠҎ্ͷϝιου໊Λఆٛ͢Δ͜ͱʹͳΔͷͰμα͍ - ϝιουͷఆ͕ٛຊདྷͷϝιουͱಉ͡৔ॴʹͳΔͷͰ֦ுର৅ΛԚછ͢Δ - ಉ͡alias_methodͷϖΞΛ2ճ࣮ߦͯ͠͠·͏ͱϝιου࣮ߦ࣌ʹࣗݾࢀরϧʔϓͰࢮ͵
  9. Good and Bad Parts of Module#prepend good - هड़͕؆ܿ -

    ϝιουͷఆ͕֦ٛுmodule಺Ͱด͍ͯ͡Δ bad - Rubyͷཧղ͕ઙ͍ͱΘ͔Γʹ͍͘ - Method WrapperҎ֎ͷ༻్Ͱ࢖͏ͱةݥ