Class: Blockster::Wrapper

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/blockster/wrapper.rb

Instance Method Summary collapse

Constructor Details

#initialize(klass = nil) ⇒ Wrapper

Returns a new instance of Wrapper.

Raises:

  • (ArgumentError)


8
9
10
11
12
# File 'lib/blockster/wrapper.rb', line 8

def initialize(klass = nil)
  @klass = klass || Blockster.default_class
  raise ArgumentError, "No class provided and no default_class configured" unless @klass
  @root_key = nil
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object (private)



119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/blockster/wrapper.rb', line 119

def method_missing(method_name, *args, &block)
  if @instance&.respond_to?(method_name)
    result = @instance.send(method_name, *args, &block)
    if result == @instance
      self
    else
      result
    end
  else
    super
  end
end

Instance Method Details

#as_json(options = nil) ⇒ Object



60
61
62
# File 'lib/blockster/wrapper.rb', line 60

def as_json(options = nil)
  to_h
end

#inspectObject



52
53
54
# File 'lib/blockster/wrapper.rb', line 52

def inspect
  to_h.inspect
end

#to_hObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/blockster/wrapper.rb', line 28

def to_h
  return {} unless @instance

  collected_attributes = {}

  # Get defined attributes
  if @instance.class.respond_to?(:attribute_types)
    @instance.class.attribute_types.keys.each do |attr_name|
      value = @instance.public_send(attr_name)
      collected_attributes[attr_name.to_sym] = convert_value_to_hash(value)
    end
  end

  # Get nested attributes
  if @instance.class.respond_to?(:nested_attributes)
    @instance.class.nested_attributes.each_key do |attr_name|
      nested_value = instance_variable_get("@#{attr_name}")
      collected_attributes[attr_name.to_sym] = nested_value&.to_h || {}
    end
  end

  collected_attributes
end

#to_hashObject



56
57
58
# File 'lib/blockster/wrapper.rb', line 56

def to_hash
  to_h
end

#to_json(options = nil) ⇒ Object



64
65
66
# File 'lib/blockster/wrapper.rb', line 64

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

#with(attributes = {}, &block) ⇒ Object

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/blockster/wrapper.rb', line 14

def with(attributes = {}, &block)
  raise ArgumentError, "Attributes must be a hash" unless attributes.is_a?(Hash)

  temp_class = Class.new(@klass)
  context = Context.new(temp_class, self)
  context.instance_eval(&block) if block_given?

  attributes = attributes[@root_key.to_s] if @root_key && attributes.key?(@root_key.to_s)

  @instance = temp_class.new
  set_nested_attributes(symbolize_keys(attributes))
  self
end