2016-12-17 56 views
0

在我的宝石,我有一类叫做Client,我想这样的操作:错号码参数错误,而建设一个可链接的红宝石API

client = Client.new 
client.content_type('pages').content_type 

这意味着我要设置一个属性,然后期待立即让它回到同一个链条中。这是我到目前为止有:

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 

顺便说一句,这个代码很臭。除非你有充分的理由,否则你不应该这样做。

+0

你能可能帮助我提高了代码的设计?更好的设计会是什么样子? –

+1

@Amit我建议'content_type'应该是你的类的'attr_accessor',所以你可以'client.content_type =“pages”'或'client.content_type#输出“pages”'。 –