Class: SuggestGrid::BaseModel

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

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



33
34
35
36
37
38
39
40
41
42
# File 'lib/suggest_grid/models/base_model.rb', line 33

def method_missing(method_sym, *arguments, &block)
  method = method_sym.to_s
  if method.end_with? '='
    instance_variable_set("@%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?(method_sym, include_private = false) ⇒ Boolean

Override for additional model properties

Returns:

  • (Boolean)


45
46
47
# File 'lib/suggest_grid/models/base_model.rb', line 45

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

#to_hashObject

Returns a Hash representation of the current object



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

def to_hash
  hash = {}
  self.instance_variables.each do |name|
    value = self.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.kind_of?(BaseModel) ? v.to_hash : v}
    elsif value.instance_of? Hash
      hash[key] = {}
      value.each do |k, v|
        hash[key][k] = v.kind_of?(BaseModel) ? v.to_hash : v
      end
    else
      hash[key] = value.kind_of?(BaseModel) ? value.to_hash : value
    end
  end
  hash
end

#to_json(options = {}) ⇒ Object

Returns a JSON representation of the curent object



27
28
29
30
# File 'lib/suggest_grid/models/base_model.rb', line 27

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