Class: OccamsRecord::Results::Row

Inherits:
Object
  • Object
show all
Defined in:
lib/occams-record/results.rb

Overview

Abstract class for result rows.

Like ActiveRecord, Boolean columns have #field? methods. However, unlike ActiveRecord, other column types do NOT.

Class Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw_values) ⇒ Row

Initialize a new result row.

Parameters:

  • raw_values (Array)

    array of raw values from db



76
77
78
79
# File 'lib/occams-record/results.rb', line 76

def initialize(raw_values)
  @raw_values = raw_values
  @cast_values = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/occams-record/results.rb', line 108

def method_missing(name, *args, &block)
  return super if args.any? or !block.nil?
  model = self.class.model_name.constantize

  if model.reflections.has_key? name.to_s
    raise MissingEagerLoadError.new(self, name)
  elsif model.columns_hash.has_key? name.to_s
    raise MissingColumnError.new(self, name)
  else
    super
  end
end

Class Attribute Details

.associationsObject

Array of associations names



64
65
66
# File 'lib/occams-record/results.rb', line 64

def associations
  @associations
end

.columnsObject

Array of column names



62
63
64
# File 'lib/occams-record/results.rb', line 62

def columns
  @columns
end

.model_nameObject

Name of Rails model



66
67
68
# File 'lib/occams-record/results.rb', line 66

def model_name
  @model_name
end

Instance Method Details

#inspectString

Returns a string with the “real” model name and raw result values.

Returns:

  • (String)


126
127
128
# File 'lib/occams-record/results.rb', line 126

def inspect
  "#<OccamsRecord::Results::Row @model_name=#{self.class.model_name} @raw_values=#{@raw_values}>"
end

#to_h(symbolize_names: false) ⇒ Hash Also known as: to_hash

Return row as a Hash (recursive).

Parameters:

  • symbolize_names (Boolean) (defaults to: false)

    if true, make Hash keys Symbols instead of Strings

Returns:

  • (Hash)

    a Hash with String or Symbol keys



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/occams-record/results.rb', line 87

def to_h(symbolize_names: false)
  hash = self.class.columns.reduce({}) { |a, col_name|
    key = symbolize_names ? col_name.to_sym : col_name
    a[key] = send col_name
    a
  }

  self.class.associations.reduce(hash) { |a, assoc_name|
    key = symbolize_names ? assoc_name.to_sym : assoc_name
    assoc = send assoc_name
    a[key] = if assoc.is_a? Array
               assoc.map { |x| x.to_h(symbolize_names: symbolize_names) }
             elsif assoc
               assoc.to_h(symbolize_names: symbolize_names)
             end
    a
  }
end