문제

Rails 문서에서 이것을 실제로 찾을 수 없었지만 'mattr_accessor' 입니다 기준 치수 결론 'attr_accessor' (Getter & Setter) 정상적인 루비에서 수업.

예를 들어. 수업에서

class User
  attr_accessor :name

  def set_fullname
    @name = "#{self.first_name} #{self.last_name}"
  end
end

예를 들어. 모듈에서

module Authentication
  mattr_accessor :current_user

  def login
    @current_user = session[:user_id] || nil
  end
end

이 헬퍼 방법은 제공됩니다 ActiveSupport.

도움이 되었습니까?

해결책

레일은 루비를 둘 다 확장합니다 mattr_accessor (모듈 액세서) 및 cattr_accessor (만큼 잘 _reader/_writer 버전). 루비로 attr_accessor Getter/Setter 메소드를 생성합니다 인스턴스, cattr/mattr_accessor getter/setter 메소드를 제공합니다 수업 또는 기준 치수 수준. 따라서:

module Config
  mattr_accessor :hostname
  mattr_accessor :admin_email
end

짧은 다음과 같습니다.

module Config
  def self.hostname
    @hostname
  end
  def self.hostname=(hostname)
    @hostname = hostname
  end
  def self.admin_email
    @admin_email
  end
  def self.admin_email=(admin_email)
    @admin_email = admin_email
  end
end

두 버전 모두 SO와 같은 모듈 수준 변수에 액세스 할 수 있습니다.

>> Config.hostname = "example.com"
>> Config.admin_email = "admin@example.com"
>> Config.hostname # => "example.com"
>> Config.admin_email # => "admin@example.com"

다른 팁

다음은 소스입니다 cattr_accessor

그리고

다음은 소스입니다 mattr_accessor

보시다시피, 그들은 거의 동일합니다.

왜 두 가지 버전이 있습니까? 때때로 당신은 글을 쓰고 싶어합니다 cattr_accessor 모듈에서 구성 정보에 사용할 수 있습니다. AVDI가 언급 한 것처럼.
하지만, cattr_accessor 모듈에서 작동하지 않으므로 모듈에서도 작동하기 위해 코드를 다소 복사했습니다.

또한, 때로는 클래스에 클래스 메소드를 작성하여 클래스에 모듈이 포함될 때마다 해당 클래스 메소드와 모든 인스턴스 메소드를 얻을 수 있습니다. mattr_accessor 또한 이것을 할 수 있습니다.

그러나 두 번째 시나리오에서는 행동이 매우 이상합니다. 다음 코드, 특히 참고 사항을 관찰하십시오 @@mattr_in_module 비트

module MyModule
  mattr_accessor :mattr_in_module
end

class MyClass
  include MyModule
  def self.get_mattr; @@mattr_in_module; end # directly access the class variable
end

MyModule.mattr_in_module = 'foo' # set it on the module
=> "foo"

MyClass.get_mattr # get it out of the class
=> "foo"

class SecondClass
  include MyModule
  def self.get_mattr; @@mattr_in_module; end # again directly access the class variable in a different class
end

SecondClass.get_mattr # get it out of the OTHER class
=> "foo"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top