From df5d74506f58d71f8156b9f8fe3718f821aae7fa Mon Sep 17 00:00:00 2001 From: Andreas Ronge Date: Sat, 20 Mar 2010 17:40:14 +0100 Subject: [PATCH] Added examples for Rails3 ActiveModel validations and serialization [#115] --- examples/active_model/serializers.rb | 25 +++++++++++++++++++++++++ examples/active_model/validation.rb | 26 ++++++++++++++++++++++++++ lib/neo4j/extensions/activemodel.rb | 8 ++++++++ 3 files changed, 59 insertions(+) create mode 100644 examples/active_model/serializers.rb create mode 100644 examples/active_model/validation.rb diff --git a/examples/active_model/serializers.rb b/examples/active_model/serializers.rb new file mode 100644 index 000000000..5b300fa14 --- /dev/null +++ b/examples/active_model/serializers.rb @@ -0,0 +1,25 @@ +$LOAD_PATH << File.expand_path(File.dirname(__FILE__) + "/../../lib") + +require 'rubygems' +require 'neo4j' +require 'neo4j/extensions/activemodel' + +class Person + include Neo4j::NodeMixin + include ActiveModel::Serializers::JSON + include ActiveModel::Serializers::Xml + + property :first_name + property :last_name + +end + + +Neo4j::Transaction.run do + person = Person.new :first_name => 'jimmy', :last_name => 'smith' + + puts "HASH: #{person.serializable_hash}" + puts "JSON: #{person.to_json}" + puts "XML : #{person.to_xml}" + +end diff --git a/examples/active_model/validation.rb b/examples/active_model/validation.rb new file mode 100644 index 000000000..ede7d238e --- /dev/null +++ b/examples/active_model/validation.rb @@ -0,0 +1,26 @@ +$LOAD_PATH << File.expand_path(File.dirname(__FILE__) + "/../../lib") + +require 'rubygems' +require 'neo4j' +require 'neo4j/extensions/activemodel' + +class Person + include Neo4j::NodeMixin + include ActiveModel::Validations + + property :first_name + property :last_name + + validates_presence_of :first_name, :last_name +end + + +Neo4j::Transaction.run do + person = Person.new + + puts person.valid? + puts person.errors.inspect + person.first_name = "Hej" + person.last_name = "hop" + puts person.valid? +end diff --git a/lib/neo4j/extensions/activemodel.rb b/lib/neo4j/extensions/activemodel.rb index 06e838b54..1e323ddee 100644 --- a/lib/neo4j/extensions/activemodel.rb +++ b/lib/neo4j/extensions/activemodel.rb @@ -3,10 +3,18 @@ require 'neo4j' require 'active_model' + module Neo4j::NodeMixin def to_model Neo4j::ActiveModel::ActiveModelFactory.instance.to_model(self) end + + def attributes + attr = props + attr.keys.each {|k| attr.delete k if k[0] == ?_} + attr + end + end module Neo4j::ActiveModel