Skip to content

Commit

Permalink
Merge pull request #1757 from linchus/master
Browse files Browse the repository at this point in the history
Add json field datatype
  • Loading branch information
mshibuya committed Feb 7, 2014
2 parents abf15c0 + 6d57cee commit acd360c
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/rails_admin/config/fields/types/all.rb
Expand Up @@ -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'
24 changes: 24 additions & 0 deletions 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
24 changes: 24 additions & 0 deletions 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
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seriously can't wait for this! 👍

Please sign in to comment.