Skip to content

Commit

Permalink
hash lookup and delegate to a method
Browse files Browse the repository at this point in the history
  • Loading branch information
tenderlove committed Oct 17, 2012
1 parent 4be2aef commit 5fd82a0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 15 deletions.
4 changes: 2 additions & 2 deletions lib/psych/scalar_scanner.rb
Expand Up @@ -38,9 +38,9 @@ def tokenize string
string
when '~', /^null$/i
nil
when /^(yes|true|on)$/i
when /^(?:yes|true|on)$/i
true
when /^(no|false|off)$/i
when /^(?:no|false|off)$/i
false
else
@string_cache[string] = true
Expand Down
41 changes: 28 additions & 13 deletions lib/psych/visitors/to_ruby.rb
Expand Up @@ -141,6 +141,12 @@ def visit_Psych_Nodes_Mapping o
return revive_hash({}, o) unless o.tag

case o.tag
when %r{
^!ruby/object:(?:Complex|Rational)$ |
^!ruby/object
}x
send METHODS[$&], o, $~

when /^!(?:str|ruby\/string)(?::(.*))?/, 'tag:yaml.org,2002:str'
klass = resolve_class($1)
members = Hash[*o.children.map { |c| accept c }]
Expand Down Expand Up @@ -206,19 +212,6 @@ def visit_Psych_Nodes_Mapping o
end
set

when '!ruby/object:Complex'
h = Hash[*o.children.map { |c| accept c }]
register o, Complex(h['real'], h['image'])

when '!ruby/object:Rational'
h = Hash[*o.children.map { |c| accept c }]
register o, Rational(h['numerator'], h['denominator'])

when /^!ruby\/object:?(.*)?$/
name = $1 || 'Object'
obj = revive((resolve_class(name) || Object), o)
obj

when /^!map:(.*)$/, /^!ruby\/hash:(.*)$/
revive_hash resolve_class($1).new, o

Expand Down Expand Up @@ -247,6 +240,28 @@ def visit_Psych_Nodes_Alias o
end

private

METHODS = {
'!ruby/object:Complex' => :complex,
'!ruby/object:Rational' => :rational,
'!ruby/object' => :object,
}

def complex o, match
h = Hash[*o.children.map { |c| accept c }]
register o, Complex(h['real'], h['image'])
end

def rational o, match
h = Hash[*o.children.map { |c| accept c }]
register o, Rational(h['numerator'], h['denominator'])
end

def object o, match
name = match.string.split(':', 2)[1] || 'Object'
revive((resolve_class(name) || Object), o)
end

def register node, object
@st[node.anchor] = object if node.anchor
object
Expand Down

0 comments on commit 5fd82a0

Please sign in to comment.