Module: MetaRPC::Callable::ClassMethods

Defined in:
lib/metarpc/callable.rb

Overview

Injected class methods

Instance Method Summary collapse

Instance Method Details

#handle_json_callable(method_name) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/metarpc/callable.rb', line 91

def handle_json_callable(method_name)
  old_method = instance_method(method_name)
  return if (@__json_rpc_hooked_methods ||= {}).key?(method_name)

  @__ignoring_added_methods = true
  params_contract = @__json_rpc_method_params
  error_handler = @__on_json_rpc_error

  define_method method_name do |*args, &block|
    case params_contract
    when nil
      raise_json_rpc_error(:invalid_params) unless args.empty?
    when Array
      validate_item(args, params_contract)
    when Hash
      raise_json_rpc_error(:invalid_params) unless args[0].is_a?(Hash)
      validate_item(args[0], params_contract)
    else
      raise_json_rpc_error(:internal_error)
    end

    old_method.bind(self).call(*args, &block)
  rescue RPCError => err
    raise err

  rescue StandardError => err
    error_handler&.call(err)
    raise_json_rpc_error(:server_error)
  end

  @__ignoring_added_methods = false
  @__json_rpc_hooked_methods[method_name] = {
    description: @__json_rpc_method_description,
    params: @__json_rpc_method_params
  }
end

#json_rpc_method(description, params: nil) ⇒ Object



132
133
134
135
136
# File 'lib/metarpc/callable.rb', line 132

def json_rpc_method(description, params: nil)
  @__next_method_is_json_rpc = true
  @__json_rpc_method_description = description
  @__json_rpc_method_params = params
end

#json_rpc_methodsObject



87
88
89
# File 'lib/metarpc/callable.rb', line 87

def json_rpc_methods
  @__json_rpc_hooked_methods
end

#method_added(method_name) ⇒ Object



138
139
140
141
142
# File 'lib/metarpc/callable.rb', line 138

def method_added(method_name)
  super
  handle_json_callable(method_name) if @__next_method_is_json_rpc && !@__ignoring_added_methods
  @__next_method_is_json_rpc = false
end

#on_json_rpc_error(&func) ⇒ Object



128
129
130
# File 'lib/metarpc/callable.rb', line 128

def on_json_rpc_error(&func)
  @__on_json_rpc_error = func
end