Class: Pluckr::Result::Object

Inherits:
Object
  • Object
show all
Defined in:
lib/pluckr/result/object.rb

Overview

Immutable, ActiveRecord-free value object.

One subclass is generated per schema level, with a plain reader per selected output. Internal aliases and presence markers never reach here.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ Object

Returns a new instance of Object.



31
32
33
34
# File 'lib/pluckr/result/object.rb', line 31

def initialize(attributes)
  @attributes = attributes.freeze
  freeze
end

Class Method Details

.build_class(outputs, label) ⇒ Object

Parameters:

  • outputs (Array<Symbol>)

    readers this level exposes

  • label (String)

    shown by #inspect



12
13
14
15
16
17
18
19
20
21
# File 'lib/pluckr/result/object.rb', line 12

def self.build_class(outputs, label)
  Class.new(self) do
    define_singleton_method(:pluckr_outputs) { outputs }
    define_singleton_method(:pluckr_label) { label }

    outputs.each do |output|
      define_method(output) { @attributes[output] }
    end
  end
end

.pluckr_labelObject



27
28
29
# File 'lib/pluckr/result/object.rb', line 27

def self.pluckr_label
  "Pluckr::Result"
end

.pluckr_outputsObject



23
24
25
# File 'lib/pluckr/result/object.rb', line 23

def self.pluckr_outputs
  []
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



58
59
60
# File 'lib/pluckr/result/object.rb', line 58

def ==(other)
  other.class == self.class && other.to_h == to_h
end

#[](key) ⇒ Object



36
37
38
# File 'lib/pluckr/result/object.rb', line 36

def [](key)
  @attributes[key.to_sym]
end

#as_json(options = nil) ⇒ Object

Without this, ActiveSupport serialises the object's ivars and render json: result emits {...}. to_json is left to ActiveSupport, which routes it back here with the caller's options.



50
51
52
# File 'lib/pluckr/result/object.rb', line 50

def as_json(options = nil)
  to_h.as_json(options)
end

#hashObject



63
64
65
# File 'lib/pluckr/result/object.rb', line 63

def hash
  [self.class, to_h].hash
end

#inspectObject Also known as: to_s



67
68
69
70
# File 'lib/pluckr/result/object.rb', line 67

def inspect
  pairs = @attributes.map { |key, value| "#{key}=#{value.inspect}" }
  "#<#{self.class.pluckr_label} #{pairs.join(", ")}>"
end

#keysObject



54
55
56
# File 'lib/pluckr/result/object.rb', line 54

def keys
  @attributes.keys
end

#pretty_print(pp) ⇒ Object



73
74
75
# File 'lib/pluckr/result/object.rb', line 73

def pretty_print(pp)
  pp.text(inspect)
end

#to_hObject Also known as: to_hash



40
41
42
43
44
# File 'lib/pluckr/result/object.rb', line 40

def to_h
  @attributes.transform_values do |value|
    value.is_a?(Object) ? value.to_h : value
  end
end