Skip to content

Instantly share code, notes, and snippets.

@thehenster
Created September 23, 2014 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thehenster/546d3d3104e88b4c925e to your computer and use it in GitHub Desktop.
Save thehenster/546d3d3104e88b4c925e to your computer and use it in GitHub Desktop.
source 'https://rubygems.org'
gem 'pg'
gem 'activerecord'
require 'rubygems'
require 'bundler/setup'
require 'pg'
require 'active_record'
require 'minitest/autorun'
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: 'localhost',
username: 'postgres',
password: '',
database: 'testy_test'
)
describe 'json typecasting' do
class Post < ActiveRecord::Base
validate :data_is_valid_json
def data=(str)
begin
super(str)
rescue JSON::ParserError
@__original_data_json_string = str
end
end
private
def data_is_valid_json
return unless @__original_data_json_string
begin
JSON.parse(@__original_data_json_string)
rescue JSON::ParserError
errors.add :data, 'invalid JSON'
end
end
end
before do
ActiveRecord::Base.connection.create_table :posts do |t|
t.json :data
end
end
after do
ActiveRecord::Base.connection.drop_table :posts
end
it 'persists using real json' do
p = Post.create data: "{\"foo\" : \"bar\"}"
assert p.persisted?
assert_equal({'foo' => 'bar'}, p.data)
end
it 'adds an error when using invalid json' do
p = Post.create data: "invalid json"
assert p.errors.any?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment