Created
September 21, 2008 21:27
-
-
Save ciaran/11910 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Serializing of Ruby objects compatible with PHP’s unserialize() function | |
# Ciarán Walsh | |
require 'enumerator' | |
class Float | |
def serialize | |
['d', self].join(':') + ';' | |
end | |
end | |
class Integer | |
def serialize | |
['i', self].join(':') + ';' | |
end | |
end | |
class String | |
def serialize | |
['s', self.length, '"' + self + '"'].join(':') + ';' | |
end | |
end | |
class Hash | |
def serialize | |
['a', self.size, '{' + keys.map {|i| i.serialize + self[i].serialize }.join + '}'].join(':') | |
end | |
end | |
class Array | |
def serialize | |
Hash[*self.enum_with_index.to_a.flatten.reverse].serialize # ["foo", "bar"] => {0 => "foo", 1 => "bar"} | |
end | |
end | |
if $0 == __FILE__ | |
require 'rubygems' | |
require 'json' | |
require 'spec' | |
def run_php(code, input) | |
IO.popen(code, 'w+') do |io| | |
io << input | |
io.close_write | |
io.read | |
end | |
end | |
class Object | |
def php_serialize | |
run_php(%q{php -r'echo serialize(json_decode(file_get_contents("php://stdin")));'}, self.to_json) | |
end | |
end | |
class Hash | |
# Since we are using JSON (which uses Objects as Hashes) to pass data to PHP, | |
# it will decode Hashes as instances of stdClass unless we cast to array | |
def php_serialize | |
run_php(%q{php -r'echo serialize((array)json_decode(file_get_contents("php://stdin")));'}, self.to_json) | |
end | |
end | |
[1, "foo", ['bar', 1, 12], {"foo" => "bar"}].each do |var| | |
var.serialize.should == var.php_serialize | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment