Permalink
Browse files

Merge pull request #1757 from linchus/master

Add json field datatype
  • Loading branch information...
2 parents abf15c0 + 6d57cee commit acd360c31fc95910caa76c2a88587c36f1c26826 @mshibuya mshibuya committed Feb 7, 2014
View
1 lib/rails_admin/config/fields/types/all.rb
@@ -26,3 +26,4 @@
require 'rails_admin/config/fields/types/ck_editor'
require 'rails_admin/config/fields/types/code_mirror'
require 'rails_admin/config/fields/types/wysihtml5'
+require 'rails_admin/config/fields/types/json'
View
24 lib/rails_admin/config/fields/types/json.rb
@@ -0,0 +1,24 @@
+require 'rails_admin/config/fields/types/text'
+
+module RailsAdmin
+ module Config
+ module Fields
+ module Types
+ class Json < RailsAdmin::Config::Fields::Types::Text
+ # Register field type for the type loader
+ RailsAdmin::Config::Fields::Types.register(self)
+
+ register_instance_option :formatted_value do
+ value.present? ? JSON.pretty_generate(value) : nil
+ end
+
+ def parse_input(params)
+ if params[name].is_a?(::String)
+ params[name] = (params[name].blank? ? nil : JSON.parse(params[name]))
+ end
+ end
+ end
+ end
+ end
+ end
+end
View
24 spec/rails_admin/config/fields/types/json_spec.rb
@@ -0,0 +1,24 @@
+require 'spec_helper'
+
+describe RailsAdmin::Config::Fields::Types::Json do
+ describe '#parse_input' do
+ let(:field) { RailsAdmin.config(FieldTest).fields.detect { |f| f.name == :json_field } }
+ before :each do
+ RailsAdmin.config do |config|
+ config.model FieldTest do
+ field :json_field, :json
+ end
+ end
+ end
+
+ it 'parse valid json string' do
+ data = {string: 'string', integer: 1, array: [1, 2, 3], object: {bla: 'foo'}}.as_json
+ expect(field.parse_input(json_field: data.to_json)).to eq data
+ end
+
+ it 'raise JSON::ParserError with invalid json string' do
+ expect { field.parse_input(json_field: '{{') }.to raise_error(JSON::ParserError)
+ end
+
+ end
+end

1 comment on commit acd360c

@whoisjake

Seriously can't wait for this! 👍

Please sign in to comment.