Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reworking OrcidValidator #4251

Merged
merged 1 commit into from Feb 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/models/concerns/hyrax/user.rb
Expand Up @@ -106,7 +106,7 @@ def normalize_orcid
# 2. the orcid field is blank
# 3. the orcid is already in its normalized form
return if errors[:orcid].first.present? || orcid.blank? || orcid.starts_with?('https://orcid.org/')
bare_orcid = Hyrax::OrcidValidator.match(orcid)
bare_orcid = Hyrax::OrcidValidator.extract_bare_orcid(from: orcid)
self.orcid = "https://orcid.org/#{bare_orcid}"
end

Expand Down
17 changes: 12 additions & 5 deletions app/models/hyrax/orcid_validator.rb
@@ -1,17 +1,24 @@
module Hyrax
class OrcidValidator < ActiveModel::Validator
ORCID_REGEXP = %r{^(?<prefix>https?://orcid.org/)?(?<orcid>\d{4}-\d{4}-\d{4}-\d{3}[\dX])/?$}
def validate(record)
return if record.orcid.blank?
record.errors.add(:orcid, 'must be a string of 19 characters, e.g., "0000-0000-0000-0000"') unless self.class.match(record.orcid)
record.errors.add(:orcid, 'must be a string of 19 characters, e.g., "0000-0000-0000-0000"') unless ORCID_REGEXP.match?(record.orcid)
end

# @deprecated
def self.match(string)
Regexp.new(orcid_regex).match(string) { |m| m[:orcid] }
Deprecation.warn "Use 'Hyrax::OrcidValidator.extract_bare_orcid(from:)'"
extract_bare_orcid_from(from: string)
end

def self.orcid_regex
'^(?<prefix>https?://orcid.org/)?(?<orcid>\d{4}-\d{4}-\d{4}-\d{3}[\dX])/?$'
# @api public
# @param [String] from
# @return nil if the given string is not in the Orcid form
# @return string of the form "0000-0000-0000-0000" if the given string conforms to Orcid's format
# @see ORCID_REGEXP
def self.extract_bare_orcid(from:)
ORCID_REGEXP.match(from) { |m| m[:orcid] }
end
private_class_method :orcid_regex
end
end