Module: SimplifyApi
- Defined in:
- lib/simplify_api/version.rb,
lib/simplify_api/simplify_api.rb
Defined Under Namespace
Modules: ClassMethods
Constant Summary
collapse
- VERSION =
"0.1.2"
Class Method Summary
collapse
Instance Method Summary
collapse
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args, &block) ⇒ Object
74
75
76
77
78
79
80
81
|
# File 'lib/simplify_api/simplify_api.rb', line 74
def method_missing(method_name, *args, &block)
case method_name
when /(.*)\=$/
create_and_set_instance_variable("#{$1}", args[0])
else
super(method_name, args, block)
end
end
|
Class Method Details
.included(base) ⇒ Object
2
3
4
5
6
7
8
9
10
|
# File 'lib/simplify_api/simplify_api.rb', line 2
def self.included(base)
base.singleton_class.send(:attr_accessor, :attributes)
base.attributes = {}
base.singleton_class.send(:attr_accessor, :mandatory)
base.mandatory = []
base.singleton_class.send(:attr_accessor, :default)
base.default = {}
base.extend(ClassMethods)
end
|
Instance Method Details
#initialize(opts) ⇒ Object
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
# File 'lib/simplify_api/simplify_api.rb', line 30
def initialize(opts)
opts = {self.class.attributes.first[0] => opts} if opts.class == Array
opts.each_pair do |k, v|
case v
when Hash
v = self.class.attributes[k.to_sym][:type].new(v)
when Array
v.collect! do |i|
self.class.attributes[k.to_sym][:params][:array_type].new(i)
end
end
create_and_set_instance_variable("#{k}", v)
end
raise ArgumentError, "Missing mandatory attributes => #{self.class.mandatory-self.instance_variables}" if not mandatory_attributes_in?
self.class.default.each_pair do |k, v|
create_and_set_instance_variable(k, v) unless self.instance_variables.include?("@#{k}".to_sym)
end
self
end
|
#respond_to_missing?(method_name, *args) ⇒ Boolean
83
84
85
86
87
88
89
90
|
# File 'lib/simplify_api/simplify_api.rb', line 83
def respond_to_missing?(method_name, *args)
case method_name
when /(.*)\=$/
true
else
super(method_name, args)
end
end
|
#to_h ⇒ Object
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
# File 'lib/simplify_api/simplify_api.rb', line 50
def to_h
h = {}
instance_variables.each do |i|
k = /\@(.*)/.match(i.to_s)[1].to_sym
v = instance_variable_get(i)
if v.class == Array then
r = []
v.each {|a| r << (a.respond_to?(:to_h) ? a.to_h : a) }
if self.class.attributes[k][:params][:invisible] then
h = r
else
h[k] = r
end
else
h[k] = v.respond_to?(:to_h) ? v.to_h : v
end
end
return h
end
|
#to_json ⇒ Object
70
71
72
|
# File 'lib/simplify_api/simplify_api.rb', line 70
def to_json
self.to_h.to_json
end
|