Open MichaelSp opened 10 years ago
I came up with an work around for that, called JsonStore:
put this into your app/models/concerns
directory
module JsonStore
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def in_json(store: :json_data, attributes:)
attributes.each do |attr_name|
define_method "#{attr_name}=".to_sym do |value|
send(store)[attr_name] = value
value
end
define_method attr_name do
send(store)[attr_name]
end
define_method store do
ivar = instance_variable_get "@#{store}".to_sym
ivar ||= (JSON.parse(self[store]) rescue {}).with_indifferent_access
instance_variable_set "@#{store}".to_sym, ivar
ivar
end
class_eval <<-EOF
before_save do
self.#{store} = @#{store}.to_json
end
EOF
end
end
end
end
And use it like this:
class Company < ActiveRecord::Base
include JsonStore
in_json store: :contact_person, attributes: [:contact_name, :email, :phone]
validates :phone, format: { with: /\A[+]*[0-9\.\\ -]+\z/, message: 'Wrong phone number'}
validates :email, uniqueness: false, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, message: 'Illegal email address'}
validates_presence_of :contact_name, :email, :phone
validates_uniqueness_of :name
end
Here is a proof of the bug: https://github.com/MichaelSp/json_record_bug
You can switch in the Gemfile between the working and the non working version and than run:
rm Gemfile.lock && bundle install && rake test
This is the error