Class: Toy::Reference::ReferenceProxy

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/toy/reference.rb

Instance Method Summary collapse

Constructor Details

#initialize(reference, owner) ⇒ ReferenceProxy

Returns a new instance of ReferenceProxy.



47
48
49
# File 'lib/toy/reference.rb', line 47

def initialize(reference, owner)
  @reference, @owner = reference, owner
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



113
114
115
# File 'lib/toy/reference.rb', line 113

def method_missing(method, *args, &block)
  target.send(method, *args, &block)
end

Instance Method Details

#build(attrs = {}) ⇒ Object



85
86
87
88
89
90
# File 'lib/toy/reference.rb', line 85

def build(attrs={})
  proxy_class.new(attrs).tap do |record|
    self.target_id = record.id
    reset
  end
end

#create(attrs = {}) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/toy/reference.rb', line 75

def create(attrs={})
  proxy_class.create(attrs).tap do |record|
    if record.persisted?
      self.target_id = record.id
      proxy_owner.save
      reset
    end
  end
end

#proxy_ownerObject



51
52
53
# File 'lib/toy/reference.rb', line 51

def proxy_owner
  @owner
end

#proxy_respond_to?Object



44
# File 'lib/toy/reference.rb', line 44

alias_method :proxy_respond_to?, :respond_to?

#replace(record) ⇒ Object



64
65
66
67
68
69
70
71
72
73
# File 'lib/toy/reference.rb', line 64

def replace(record)
  if record.nil?
    reset
    self.target_id = nil
  else
    assert_type(record)
    @target = record
    self.target_id = record.id
  end
end

#resetObject



60
61
62
# File 'lib/toy/reference.rb', line 60

def reset
  @target = nil
end

#respond_to?(*args) ⇒ Boolean

Does the proxy or its target respond to symbol?

Returns:



93
94
95
# File 'lib/toy/reference.rb', line 93

def respond_to?(*args)
  proxy_respond_to?(*args) || target.respond_to?(*args)
end

#targetObject



55
56
57
58
# File 'lib/toy/reference.rb', line 55

def target
  return nil if target_id.blank?
  @target ||= proxy_class.get(target_id)
end