Skip to content

Commit

Permalink
Documenting, and fixing a bug in, typecasting feature.
Browse files Browse the repository at this point in the history
  • Loading branch information
jcoglan committed Jun 29, 2009
1 parent c45adba commit 63da21a
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
28 changes: 26 additions & 2 deletions README.rdoc
Expand Up @@ -2,8 +2,8 @@

* http://github.com/jcoglan/siren

Siren is a JSON and JSONQuery interpreter for Ruby. It extends the normal process
process of JSON-to-Ruby processing with cross-references, automatic typecasting,
Siren is a JSON and JSONQuery interpreter for Ruby. It extends the normal functionality
of JSON-to-Ruby processing with cross-references, automatic typecasting,
and a succinct query language for filtering JSON and Ruby object graphs.


Expand Down Expand Up @@ -52,6 +52,30 @@ The general syntax for a cross-reference is <tt>{"$ref": ID_STRING}</tt>; the pa
will replace this with the referenced object in the Ruby output.


=== Automatic typecasting

JSON parsers typically output hashes and arrays, these being Ruby's closest analogues
to the JavaScript types that JSON expresses. Siren allows objects to be imbued with
a +type+ attribute, which if present causes the parser to cast the object to an
instance of the named type instead of a hash. Instead of hash keys, the keys in the
JSON object become instance variables of the typed object. To allow the parser to use
a class for casting, it must be extended using <tt>Siren::Node</tt>:

class PersonModel
extend Siren::Node
end

data = Siren.parse <<-JSON
{
"type": "person_model",
"name": "Jimmy",
"age": 25
}
JSON

#=> #<PersonModel @type="person_model", @age=25, @name="Jimmy">


== Install

sudo gem install siren
Expand Down
2 changes: 2 additions & 0 deletions lib/siren.rb
Expand Up @@ -45,6 +45,8 @@ def self.parse(string, &block)
value
end

result = Node.from_json(result)

Reference.resolve!(result, @symbols)
@json_parser.walk(result, &block) if block_given?

Expand Down
2 changes: 2 additions & 0 deletions test/test_siren.rb
Expand Up @@ -51,6 +51,8 @@ def test_casting
mike = Person.new('ford')
bob = Person.new('bentley', 'ferrari', 'zonda')
assert_equal( {"people" => [mike, bob]}, fixtures(:people) )

assert_kind_of Person, Siren.parse('{"type": "person"}')
end

def test_referencing
Expand Down

0 comments on commit 63da21a

Please sign in to comment.