forked from tauraloke/ruby-method-missing-test
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_db.rb
More file actions
71 lines (51 loc) · 1.28 KB
/
json_db.rb
File metadata and controls
71 lines (51 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# frozen_string_literal: true
require 'json'
require_relative './common_methods'
class JsonDb
include CommonMethods
def initialize(json_filename)
@json_filename = json_filename
end
attr_reader :json_filename
def data
@data ||= JSON.parse(IO.read(json_filename))
end
private
# Use this method to store updated properties on disk
def serialize
IO.write(json_filename, data.to_json)
end
def method_missing(method_name, *args)
method_str = method_name.to_s
if method_str.end_with? '='
data[method_str.gsub('=', '')] = args.first
serialize
args.first
else
add_class_attribute(method_str, data)
updated_data = data[method_str]
serialize
updated_data
end
end
end
class Hash
include CommonMethods
undef_method :class
private
def method_missing(method_name, *args)
method_str = method_name.to_s
if method_str == 'class'
create_class(self['class_name'])
elsif method_str.include? '='
self[method_str.gsub('=', '')] = args.first
else
add_class_attribute(method_str, self)
self[method_str]
end
end
def create_class(class_name)
Object.const_set(class_name, Class.new) unless Object.const_defined?(class_name)
Object.const_get(class_name)
end
end