< :前の番号
^ :番号順リスト
> :次の番号
P :前の記事(スレッド移動)
N :次の記事
|<:前のスレッド
>|:次のスレッド
^ :返事先
_:自分への返事
>:同じ返事先を持つ記事(前)
<:同じ返事先を持つ記事(後)
---:分割してスレッド表示、再表示
| :分割して(縦)スレッド表示、再表示
~ :スレッドのフレーム消去
.:インデックス
..:インデックスのインデックス
Issue #14059 has been reported by kddeisz (Kevin Deisz).
----------------------------------------
Feature #14059: Refine multiple classes in one call
https://bugs.ruby-lang.org/issues/14059
* Author: kddeisz (Kevin Deisz)
* Status: Open
* Priority: Normal
* Assignee:
* Target version:
----------------------------------------
Consider the following problem - I would like to be able to validate that a JSON string contains all things that can represent positive integers. In this case, it works well with refinements, because I can:
~~~
class PositiveJSONValidator < ActiveModel::EachValidator
using Module.new {
refine String do
def positive_integer?
match?(/[1-9](?:[0-9])*/)
end
end
refine Integer do
def positive_integer?
self > 0
end
end
refine Float do
def positive_integer?
self == self.to_i
end
end
refine NilClass do
def positive_integer?
false
end
end
refine Array do
def positive_integer?
false
end
end
refine Hash do
def positive_integer?
false
end
end
}
def validate_each(record, attribute, value)
return if valid_positive_json?(value)
record.errors[attribute] << options[:message] || 'is invalid'
end
private
def valid_positive_json?(value)
JSON.parse(value).all? do |key, value|
key.positive_integer? && value.positive_integer?
end
rescue JSON::ParserError
false
end
end
~~~
However, this is kind of annoying because I need to specify each class manually. What I'd love to be able to do is group classes by passing all of the ones that need to be refined in the same way, as in:
~~~
refine NilClass, Array, Hash do
def positive_integer?
false
end
end
~~~
Is this something that people would consider? It seems like a good use case for refinements because I just want to send a message to an object, so basically I want a default case. I could just refine Object but that feels wrong, I'd rather get an undefined method exception so that I know something unexpected occurred. If accepted I'd be happy to submit a patch.
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>