Rails의 보호 및 비공개 메서드
Ruby의 메소드 가시성 (공개, 보호 및 비공개 메소드) 은이 블로그 게시물 과 같은 곳에서 잘 설명되었습니다 . 하지만 Ruby on Rails에서는 프레임 워크가 설정되는 방식 때문에 일반 Ruby 애플리케이션에서와 약간 다르게 보입니다. 그렇다면 Rails 모델, 컨트롤러, 헬퍼, 테스트 등에서 보호 된 메서드 나 프라이빗 메서드를 사용하는 것이 적절하지 않은가?
편집 : 지금까지 답변 해 주셔서 감사합니다. Ruby에서 protected 및 private의 개념을 이해하지만 이러한 유형의 가시성이 Rails 앱 (모델, 컨트롤러, 도우미, 테스트)의 컨텍스트 내에서 사용되는 일반적인 방법에 대한 설명을 더 찾고 있습니다. . 예를 들어, 공용 컨트롤러 메서드는 작업 메서드이고, 응용 프로그램 컨트롤러의 보호 된 메서드는 여러 컨트롤러에서 액세스해야하는 "도우미 메서드"등에 사용됩니다.
모델의 경우 공용 메서드가 클래스의 공용 인터페이스라는 아이디어가 있습니다. 공용 메서드는 다른 개체에 의해 사용되는 반면 보호 / 개인 메서드는 외부에서 숨겨집니다.
이것은 다른 객체 지향 언어에서와 동일한 관행입니다.
들어
컨트롤러와
당신이 원하는대로 테스트, 단지 않습니다.
컨트롤러와 테스트 클래스는 모두
프레임 워크에 의해 인스턴스화되고 호출됩니다 (
예, 이론적으로보기에서 컨트롤러를 가져올 수 있다는 것을 알고 있지만 그렇게하면 어쨌든 이상한 것이 있습니다
). 아무도 이러한 것들을 직접 만들지 않기 때문에 "보호"할 것이 없습니다.
부록 / 수정 : 컨트롤러의 경우 "도우미"메서드를
보호 된
개인 으로 표시
해야하며 작업 자체 만 공용이어야합니다. 프레임 워크는 들어오는 HTTP 호출을 공개되지 않은 작업 / 메소드로 라우팅하지 않으므로 도우미 메서드는 이러한 방식으로 보호되어야합니다.
도우미의 경우 메서드가 항상 "직접"으로 호출되기 때문에 메서드가 보호되거나 비공개인지 여부에 차이가 없습니다.
물론 이해하기 쉽도록 모든 경우에 보호 된 항목을 표시 할 수 있습니다.
다른 사람이 아니라self
메서드를 사용하려면 개인 메서드 를 사용합니다. self and is_a?(self)
s 만 호출 할 수있는 것을 원한다면 보호 된 메서드를 사용합니다 .
protected는 "가상"초기화 방법이있는 경우 유용 할 수 있습니다.
class Base
def initialize()
set_defaults()
#other stuff
end
protected
def set_defaults()
# defaults for this type
@foo = 7
calculate_and_set_baz()
end
private
def calculate_and_set_baz()
@baz = "Something that only base classes have like a file handle or resource"
end
end
class Derived < Base
protected
def set_defaults()
@foo = 13
end
end
@foo는 다른 값을 갖습니다. 파생 인스턴스에는 @baz가 없습니다.
업데이트 :이 글을 쓴 이후로 Ruby 2.0+에서 몇 가지 사항이 변경되었습니다. Aaron Patterson은 훌륭한 글을 작성했습니다. http://tenderlovemaking.com/2012/09/07/protected-methods-and-ruby-2-0.html
The difference between protected and private is subtle. If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object---it is never possible to access another object instance's private methods directly, even if the object is of the same class as the caller. For protected methods, they are accessible from objects of the same class (or children).
http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Declaring_Visibility
You seem to have a good idea of the semantics of class visibility (public/protected/private) as applied to methods. All I can offer is a quick outline of the way I implement it in my Rails apps.
I implement protected methods in the base application controller so they can get called by any controller via filters (e.g. before_filter :method_foo). In a similar way, I define protected methods for models that I want to use in all of them in a base model that they all inherit from.
Although actions need to be public methods of a controller, not all public methods are necessarily actions. You can use hide_action
if you're using a catch-all route like /:controller/:action/:id
or if it's disabled (the default in Rails 3) then only methods with explicit routes will be called.
This can be useful if you're passing the controller instance to some other library like the Liquid template engine as you can provide a public interface rather than having to use send in your Liquid filters and tags.
참고URL : https://stackoverflow.com/questions/4495078/protected-and-private-methods-in-rails
'Nice programing' 카테고리의 다른 글
동적 높이가있는 행이있는보기 기반 NSTableView (0) | 2020.10.04 |
---|---|
큰 파일을 자르는 Unix 쉘 스크립트 (0) | 2020.10.04 |
"모두 제외"jQuery 선택기 (0) | 2020.10.04 |
Ruby 블록에서 'return'사용 (0) | 2020.10.04 |
ArrayList를 스레드로부터 안전하게 만드는 방법은 무엇입니까? (0) | 2020.10.04 |