2016-12-17 4 views
0

를 구축하는 동안 나는 클래스 I는 다음과 같이 작동 원하는 Client라는이 즉시 같은 체인에서 다시 가져 오십시오.잘못된 번호 내 보석에서 체인 방식 루비에게 API를

class Client 
    attr_reader :content_type 

    def initialize(options = {}) 
    @options = options 
    end 

    def content_type 
    @content_type 
    end 

    def content_type(type_id) 
    @content_type = type_id 
    self 
    end 
end 

을 이제 내가 얻을 client.content_type('pages').content_type를 실행하려고하면 : 내가 잘못

wrong number of arguments (given 0, expected 1) (ArgumentError) 
    from chaining.rb:16:in `<main>' 

를하고있는 중이 야 무엇 이것은 내가 지금까지 가지고 무엇인가? 이것을 정확하게 쓰려면 어떻게해야합니까?

답변

1

귀하의 방법 이름이 충돌합니다. 두 번째 방법은 첫 번째 방법을 우선합니다. 어느 다른 이름을 사용하거나 모두 같은 작업을 수행하기 위해 통합 :

class Client 
    attr_reader :content_type 

    def initialize(options = {}) 
    @options = options 
    end 

    def content_type(type_id = nil) 
    type_id ? @content_type : set_content_type(type_id) 
    end 

    def set_content_type(type_id) 
    @content_type = type_id 
    self 
    end 
end 

, BTW이 코드는 냄새. 정당한 이유가없는 한 그렇게해서는 안됩니다.

+0

코드 디자인 개선에 도움을 주시겠습니까? 더 나은 디자인은 어떻게 생겼습니까? –

+1

@content_type은 클래스의'attr_accessor'이어야한다. 그래서'client.content_type = "pages"'또는'client.content_type # output "pages"를 할 수있다. –