Skip to content

Instantly share code, notes, and snippets.

@harlanbarnes
Last active August 29, 2015 14:06
Show Gist options
  • Save harlanbarnes/d38934f96abc41347a7a to your computer and use it in GitHub Desktop.
Save harlanbarnes/d38934f96abc41347a7a to your computer and use it in GitHub Desktop.
Generating ruby code from JSON or other ruby objects ...
#!/usr/bin/env ruby
def typecast(obj)
if obj.is_a?(Hash) || obj.is_a?(Array)
# hashes and arrays will be inspected to display properly
obj.inspect
elsif obj.is_a?(Fixnum) || obj.is_a?(Float) ||
obj.is_a?(TrueClass) || obj.is_a?(FalseClass)
# these are just plain (that is obj.to_s does what we want)
obj
elsif obj.is_a?(Symbol)
# symbols should remain symbols
":#{obj}"
else
# must be a string so let's try to convert to a ruby type
case obj
when /^:/
# found symbol
obj
when /^\{/
# found hash
obj.inspect
when /^\[/
# found array
obj.inspect
when /^true$|^false$/
# found boolean
obj
when /[0-9.]+/
# found Fixnum or Floar
obj
else
# leave it as a string
"\"#{obj}\""
end
end
end
require 'json'
json = '{
"boolean_true_test": "true",
"boolean_false_test": "false",
"integer_test": "42",
"fixnum_test": "10.42",
"symbol_test": ":shell",
"string_test": "string_value",
"hash_test": {
"string_type": "string_value",
"array_type": [
"1", "2", "3"
]
},
"array_test": [ "will", "libby", "jack" ]
}'
puts "JSON testing ..."
JSON.parse(json).each do |k,v|
value = typecast(v)
puts "#{k} --> #{value}"
end
puts
puts "Ruby type (wrapper cookbook) testing ..."
puts "True: " + typecast(true).to_s
puts "False: " + typecast(false).to_s
puts "Fixnum: " + typecast(10).to_s
puts "Float: " + typecast(10.42).to_s
puts "Hash: " + typecast({ "foo" => "bar" }).to_s
puts "Array: " + typecast([ "foo", "bar", "baz"]).to_s
puts "Symbol: " + typecast(:shell).to_s
JSON testing ...
boolean_true_test --> true
boolean_false_test --> false
integer_test --> 42
fixnum_test --> 10.42
symbol_test --> :shell
string_test --> "string_value"
hash_test --> {"string_type"=>"string_value", "array_type"=>["1", "2", "3"]}
array_test --> ["will", "libby", "jack"]
Ruby type (wrapper cookbook testing) ...
True: true
False: false
Fixnum: 10
Float: 10.42
Hash: {"foo"=>"bar"}
Array: ["foo", "bar", "baz"]
Symbol: :shell
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment