development

루비 : 자기 확장

big-blog 2020. 7. 26. 11:38
반응형

루비 : 자기 확장


루비에서는의 기본 아이디어를 이해합니다 extend. 그러나이 코드 세그먼트에서 어떤 일이 일어나고 있습니까? 구체적으로 무엇을 extend합니까? 인스턴스 메소드를 클래스 메소드로 만드는 편리한 방법입니까? 처음부터 클래스 메소드를 지정하지 않고 왜 이런 식으로 하시겠습니까?

module Rake
  include Test::Unit::Assertions

  def run_tests # etc.
  end

  # what does the next line do?
  extend self
end

인스턴스 메소드를 클래스 메소드로 만드는 편리한 방법입니다. 그러나 더 효율적인 싱글 톤 으로 사용할 수도 있습니다 .


모듈에서 self는 모듈 클래스 자체입니다. 예를 들어

puts self

갈퀴를 반환합니다,

extend self

기본적으로 Rake에 정의 된 인스턴스 메소드를 사용할 수 있도록합니다.

Rake.run_tests

나를 위해 항상 생각하는 데 도움이 extend같은 include싱글 톤 클래스 (또한 메타 또는 고유 클래스라고도 함) 내부.

싱글 톤 클래스 내에 정의 된 메소드는 기본적으로 클래스 메소드라는 것을 알고있을 것입니다.

module A
  class << self
    def x
      puts 'x'
    end
  end
end

A.x #=> 'x'

이제 우리는 알고 있다는 extendinclude, 따라서 단일 클래스 내부와 모듈의 방법은 클래스 메소드로 노출 :

module A
  class << self
    include A

    def x
      puts 'x'
    end
  end

  def y
    puts 'y'
  end
end

A.x #=> 'x'
A.y #=> 'y'

링크 부패를 피하기 위해 user83510이 링크 한 Chris Wanstrath블로그 게시물이 아래에 다시 게시됩니다 (허가 됨). 그래도 원본을 능가하는 것은 없으므로 계속 작동하는 한 그의 링크를 사용하십시오.


→ 싱글 톤 노래하기 2008 년 11 월 18 일 내가 이해하지 못하는 것들이있다. 예를 들어 데이빗 보위 아니면 남반구. 그러나 Ruby의 Singleton처럼 내 마음을 어지럽히는 것은 없습니다. 실제로는 완전히 불필요합니다.

다음은 코드를 사용하여 수행하려는 작업입니다.

require 'net/http'

# first you setup your singleton
class Cheat
  include Singleton

  def initialize
    @host = 'http://cheat.errtheblog.com/'
    @http = Net::HTTP.start(URI.parse(@host).host)
  end


  def sheet(name)
    @http.get("/s/#{name}").body
  end
end

# then you use it
Cheat.instance.sheet 'migrations'
Cheat.instance.sheet 'yahoo_ceo'

그러나 그것은 미쳤다. 힘을 싸워라.

require 'net/http'

# here's how we roll
module Cheat
  extend self

  def host
    @host ||= 'http://cheat.errtheblog.com/'
  end

  def http
    @http ||= Net::HTTP.start(URI.parse(host).host)
  end

  def sheet(name)
    http.get("/s/#{name}").body
  end
end

# then you use it
Cheat.sheet 'migrations'
Cheat.sheet 'singletons'

Any why not? The API is more concise, the code is easier to test, mock, and stub, and it’s still dead simple to convert into a proper class should the need arise.

(( copyright ought ten chris wanstrath ))


extend self includes all the existing instance methods as module methods. This is equivalent to saying extend Rake. Also Rake is an object of class Module.

Another way to achieve equivalent behavior will be:

module Rake
  include Test::Unit::Assertions

  def run_tests # etc.
  end

end 

Rake.extend(Rake)

This can be used to define self contained modules with private methods.

참고URL : https://stackoverflow.com/questions/1733124/ruby-extend-self

반응형