Skip to content

Commit

Permalink
added ValidationsRepresenter to jsonify and deserialize ActiveModel v…
Browse files Browse the repository at this point in the history
…alidations.
  • Loading branch information
apotonick committed Jan 20, 2012
1 parent cab90a6 commit fcb42cc
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
25 changes: 25 additions & 0 deletions lib/roar/rails/validations_representer.rb
@@ -0,0 +1,25 @@
require 'representable/json/collection'
require 'representable/json/hash'

# Represents a validators hash for a model.
module ValidatorsRepresenter
class ValidatorClient
attr_accessor :kind, :options
end

# Represents a single Validator instance.
module ValidatorRepresenter
include Roar::Representer::JSON
property :kind
hash :options
end

# Represents an array of validators for an attribute.
module AttributeValidators
include Representable::JSON::Collection
items :extend => ValidatorRepresenter, :class => ValidatorClient
end

include Representable::JSON::Hash
values :extend => AttributeValidators, :class => Array
end
34 changes: 34 additions & 0 deletions test/validations_test.rb
@@ -0,0 +1,34 @@
require 'test_helper'
require 'active_model'
require 'roar/rails/validations_representer'


class ValidationsTest < MiniTest::Spec
class Comment
include ActiveModel::Validations
validates :name, :presence => true
end

describe "ValidatorRepresenter" do
it "renders a representation in #to_json" do
assert_equal "{\"kind\":\"presence\",\"options\":{}}", Comment._validators[:name].first.extend(ValidatorsRepresenter::ValidatorRepresenter).to_json
end

it "parses validator config in #from_json" do
validator = ValidatorsRepresenter::ValidatorClient.new.extend(ValidatorsRepresenter::ValidatorRepresenter).from_json("{\"kind\":\"presence\",\"attributes\":[\"name\"],\"options\":{}}")
assert_equal "presence", validator.kind
assert_equal({}, validator.options)
end
end

describe "ValidatorsRepresenter" do
it "renders a collection in #to_json" do
assert_equal "{\"name\":[{\"kind\":\"presence\",\"options\":{}}]}", Comment._validators.extend(ValidatorsRepresenter).to_json
end

it "parses validators in #from_json" do
validations = {}.extend(ValidatorsRepresenter).from_json("{\"name\":[{\"kind\":\"presence\",\"options\":[]}]}")
assert_equal "presence", validations["name"].first.kind
end
end
end

0 comments on commit fcb42cc

Please sign in to comment.