Class: JsonFunc
- Inherits:
-
Object
show all
- Defined in:
- lib/json_func.rb
Defined Under Namespace
Classes: BadFunctionNameError, BadRootObject, MultipleFunctionsError, ZeroFunctionsError
Instance Attribute Summary collapse
Instance Method Summary
collapse
Constructor Details
#initialize(handler) ⇒ JsonFunc
Returns a new instance of JsonFunc.
10
11
12
|
# File 'lib/json_func.rb', line 10
def initialize(handler)
@handler = handler
end
|
Instance Attribute Details
#handler ⇒ Object
Returns the value of attribute handler.
8
9
10
|
# File 'lib/json_func.rb', line 8
def handler
@handler
end
|
Instance Method Details
#execute(json) ⇒ Object
14
15
16
17
18
|
# File 'lib/json_func.rb', line 14
def execute(json)
initial_argument = JSON.parse(json)
raise BadRootObject unless initial_argument.is_a? Hash
execute_hash(initial_argument)
end
|
#execute_hash(hash) ⇒ Object
20
21
22
23
24
25
26
27
|
# File 'lib/json_func.rb', line 20
def execute_hash(hash)
raise MultipleFunctionsError.new(hash.keys) if hash.size > 1
raise ZeroFunctionsError.new(hash.keys) if hash.size == 0
func = hash.keys.first
raise BadFunctionNameError.new(func) unless valid_function?(func)
arg = hash.values.first
handler.send(func, *parse_arg(arg))
end
|
#parse_arg(arg) ⇒ Object
33
34
35
36
37
38
39
40
41
42
|
# File 'lib/json_func.rb', line 33
def parse_arg(arg)
case arg
when Hash
execute_hash(arg)
when Array
arg
else
[arg]
end
end
|
#valid_function?(func) ⇒ Boolean
29
30
31
|
# File 'lib/json_func.rb', line 29
def valid_function?(func)
(handler.public_methods - Object.new.public_methods).map(&:to_s).include? func
end
|