2016-09-28 2 views
1

모듈을 포함하는 클래스에 대해 DSL 구성을 만들려고 시도했지만 클래스와 인스턴스 메소드 모두에 대해 구성된 변수를 사용하려면 액세스 메소드로 모듈을 버려야하는 것처럼 보입니다. 이 일을 더 우아한 방법이 있습니까?루비 클래스 인스턴스 변수 설정 패턴

module DogMixin 
    class << self 
    def included(base) 
     base.extend ClassMethods 
    end 
    end 

    module ClassMethods 
    def breed(value) 
     @dog_breed = value 
    end 

    def dog_breed 
     @dog_breed 
    end 
    end 
end 

class Foo 
    include DogMixin 

    breed :havanese 
end 

puts Foo.dog_breed 
# not implemented but should be able to do this as well 
f = Foo.new 
f.dog_breed 
+0

아직 질문을 완전히받지 못했습니다. 'f = Foo.new에서 기대할 수있는 결과는 무엇입니까? f.dog_breed = : 침팬지; Foo.dog_breed'를 넣으시겠습니까? 반원들에게 어떤 상수제가 도움이됩니까? – Felix

답변

1

귀하의 예를 들어 내가 어쨌든 :) 생각 좀 이상해의 접근을 작성하지 않도록하는 한 가지 방법합니다 (할당 - 접근이 내 눈에 문제가 - 특히 주어진 예제) 상수를 정의하는 것입니다 , 아래 예제와 같이. 그러나 런타임 할당이 필요하다면 런타임 상수 할당을 엉망으로 만들고 싶을 때를 제외하고는 질문을 편집하십시오.

module DogMixin 
    # **include** DogMixin to get `Class.dog_breed` 
    class << self 
    def included(base) 
     def base.dog_breed 
     self::DOG_BREED || "pug" 
     end 
    end 
    end 

    # **extend** DogMixin to get `instance.dog_breed` 
    def dog_breed 
    self.class.const_get(:DOG_BREED) || "pug" 
    end 
end 

class Foomer 
    DOG_BREED = 'foomer' 
    extend DogMixin 
    include DogMixin 
end 

f = Foomer.new 
puts Foomer.dog_breed 
puts f.dog_breed 

# If I understand you correctly, this is the most important (?): 
f.dog_breed == Foomer.dog_breed #=> true 

그것은 모듈에서 인스턴스와 클래스 상수 조회를 얻을 수 (In Ruby) allowing mixed-in class methods access to class constants의 일부 독서를했다,하지만 작동합니다. 나는 정말로 솔루션을 좋아하는지 잘 모르겠다. 작은 질문을 추가 할 수 있지만 좋은 질문입니다.

+0

네, 예를 조금 무작위, 그것은 구성에 대한 더 많은 예를 들어 상속 (번식 <개)하지만 좋은 답변을 감사 할 수 처리 할 수 ​​있도록 :) – kreek