2013-11-27 20 views
1

让我们说我有这样的对象:有条件的关键参数(红宝石2.0)

class Post 
    def initialize(title: 'title', content: 'content') 
    @title = title 
    @content = content 
    end 
end 

,但我想补充的逻辑,如:

class Post 
    def initialize(title: 'title', content: 'content') 
    @title = title unless title.empty? # if it's empty I'd like to use the default value 
    @content = content unless content.empty? 
    end 
end 

在上面的例子中,我怎么分配关键字参数有条件?

+1

你的问题的essense是否是一个方法(不只是'initialize')可以获取它传递参数的默认值。您可以使用[Kernel#caller](http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-caller)获取调用方法,以及有关[Method @#参数](http://www.ruby-doc.org/core-2.0.0/Method.html#method-i-parameters)。考虑到可以计算默认值并且Ruby没有理由让它们可用于被调用的方法,我非常怀疑是否有办法从被调用的方法中获取它们。然而,.. –

+1

...你可能会看看[merb gem]的'get_args'方法(http://rubydoc.info/github/merb/merb/master/GetArgs)。 –

回答

1

我觉得这里有代码味道。您正尝试在两个分离的条件下将默认值分配给变量:未给出参数且参数为空时。这不是一个好设计。这是错误的潜在原因,并且使维护变得困难。我建议你应该采取的方式有两种:

(我)使参数obilgatory(即通过nil或空值,而不是不传递参数),并做验证的方法体:

class Post 
    def initialize(title, content) 
    @title = title.nil? || title.empty? ? "title" : title 
    @content = content.nil? || content.empty? ? "content" : content 
    end 
end 

(II),而不是传递一个空值作为参数,不传递它:

class Post 
    def initialize(title: "title", content: "content") 
    @title, @content = title, content 
    end 
end 
+0

谢谢,我def了解了一些:) – shicholas

1
为什么

在不单独的方法设置默认值,然后在初始化传递的参数合并?如果参数没有被传递,那么默认值就会启动。否则,默认值会被初始化时传入的参数覆盖。

例如:

class Post 
    def initialize(options) 
    options = defaults.merge(options) 
    @title = options[:title] 
    @content = options[:content] 
    end 

    def defaults 
    { 
     title: "Your Default Title" 
     content: "Your Default Content" 
    } 
    end 
... 
end