Class: Tester::BaseModel

Inherits:
Object
  • Object
show all
Defined in:
lib/tester/models/base_model.rb

Overview

Base model.

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_sym, *arguments, &block) ⇒ Object

Use to allow additional model properties.



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/tester/models/base_model.rb', line 35

def method_missing(method_sym, *arguments, &block)
  method = method_sym.to_s
  if method.end_with? '='
    instance_variable_set(format('@%s', [method.chomp('=')]),
                          arguments.first)
  elsif instance_variable_defined?("@#{method}") && arguments.empty?
    instance_variable_get("@#{method}")
  else
    super
  end
end

Instance Method Details

#respond_to_missing?(method_sym, include_private = false) ⇒ Boolean

Override for additional model properties.

Returns:

  • (Boolean)


48
49
50
# File 'lib/tester/models/base_model.rb', line 48

def respond_to_missing?(method_sym, include_private = false)
  instance_variable_defined?("@#{method_sym}") ? true : super
end

#to_hashObject

Returns a Hash representation of the current object.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/tester/models/base_model.rb', line 8

def to_hash
  hash = {}
  instance_variables.each do |name|
    value = instance_variable_get(name)
    name = name[1..-1]
    key = self.class.names.key?(name) ? self.class.names[name] : name
    if value.instance_of? Array
      hash[key] = value.map { |v| v.is_a?(BaseModel) ? v.to_hash : v }
    elsif value.instance_of? Hash
      hash[key] = {}
      value.each do |k, v|
        hash[key][k] = v.is_a?(BaseModel) ? v.to_hash : v
      end
    else
      hash[key] = value.is_a?(BaseModel) ? value.to_hash : value
    end
  end
  hash
end

#to_json(options = {}) ⇒ Object

Returns a JSON representation of the curent object.



29
30
31
32
# File 'lib/tester/models/base_model.rb', line 29

def to_json(options = {})
  hash = to_hash
  hash.to_json(options)
end