Created
April 6, 2012 19:57
-
-
Save rf-/2322543 to your computer and use it in GitHub Desktop.
Demonstrate validation of arbitrary fields (e.g., hstore)
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
#!/usr/bin/env ruby | |
require 'active_record' | |
ActiveRecord::Base.establish_connection( | |
:adapter => 'sqlite3', | |
:database => ':memory:' | |
) | |
ActiveRecord::Schema.define do | |
create_table :documents, :force => true do |t| | |
end | |
end | |
module HstoreValidation | |
def validates_hstore(field, &block) | |
validation_class = Class.new do | |
include ActiveModel::Validations | |
def self.name | |
'(validations)' | |
end | |
def initialize(data) | |
@data = data | |
end | |
def read_attribute_for_validation(attr_name) | |
@data[attr_name] | |
end | |
end | |
validation_class.class_eval &block | |
validate do | |
validator = validation_class.new(self[field]) | |
if validator.invalid? | |
validator.errors.each do |attr, text| | |
self.errors.add(attr, text) | |
end | |
end | |
end | |
end | |
end | |
class Document < ActiveRecord::Base | |
extend HstoreValidation | |
validates_hstore :data do | |
validates_length_of :title, :maximum => 50 | |
end | |
end | |
d = Document.new | |
d[:data] = {title: 'abc' * 51} | |
p d.valid? | |
p d.errors | |
d[:data][:title] = 'shorter title' | |
p d.valid? | |
p d.errors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://stackoverflow.com/questions/25783538/rails-4-1-validation-of-arbitrary-fields-via-hstore/