Module: JsonAttributes::Mixin

Defined in:
lib/json-attributes.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



6
7
8
# File 'lib/json-attributes.rb', line 6

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#create_from_json(json) ⇒ Object



74
75
76
77
78
79
80
# File 'lib/json-attributes.rb', line 74

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

#report_to_jsonObject



52
53
54
55
56
57
# File 'lib/json-attributes.rb', line 52

def report_to_json
  self.class.json_readers.inject({}) do |hash, reader|
    hash[reader] = send reader
    hash
  end.to_json
end

#update_from_json(json) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/json-attributes.rb', line 59

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