Sha256: 834ca70f6ef134eae00b2f69bd0c324c63c66f1899ba10e73bd47fb92ff275e0
Contents?: true
Size: 1.84 KB
Versions: 1
Compression:
Stored size: 1.84 KB
Contents
require 'json/ext' require File.expand_path(File.dirname(__FILE__) + '/monkey_patches') module JsonAttributes module Mixin def self.included(base) base.extend ClassMethods end module ClassMethods def json_reader(*syms) attr_reader *syms json_readers.concat(syms) end def json_writer(*syms) attr_writer *syms json_writers.concat(syms) end def json_accessor(*syms) attr_accessor *syms json_readers.concat(syms) json_writers.concat(syms) end def json_conditioner(*syms) json_conditioners.concat(syms) end def json_validator(*syms) json_validators.concat(syms) end def json_readers @json_readers ||= [] end def json_writers @json_writers ||= [] end def json_conditioners @json_conditioners ||= [] end def json_validators @json_validators ||= [] end end def report_to_json self.class.json_readers.inject({}) do |hash, reader| hash[reader] = send reader hash end.to_json end def update_from_json(json) parsed = JSON.parse(json).symbolize_keys! self.class.json_conditioners.each do |conditioner| parsed = send(conditioner, parsed) end self.class.json_validators.each do |validator| send(validator, parsed) end parsed.each_pair do |key, value| self.send("#{key}=", value) if self.class.json_writers.include?(key.to_sym) end end def create_from_json(json) parsed = JSON.parse(json) raise "Attempt to create without all the required json elements" unless self.class.json_writers.all? do |required| parsed.has_key?(required.to_s) end update_from_json(json) end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
kissifer-json-attributes-0.0.0 | lib/json-attributes.rb |