Module: AssetLink::Associations::ClassMethods

Defined in:
app/models/asset_link.rb

Instance Method Summary collapse

Instance Method Details

#has_one_as_child(name, scope) ⇒ Object

rubocop:todo Metrics/MethodLength



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'app/models/asset_link.rb', line 52

def has_one_as_child(name, scope) # rubocop:todo Metrics/MethodLength
  plural_name = name.to_s.pluralize.to_sym
  has_many(plural_name, scope, through: :links_as_child, source: :ancestor)
  line = __LINE__ + 1
  class_eval(
    "
    def #{name}
      #{plural_name}.first
    end

    def #{name}=(value)
      raise RuntimeError, 'Value for #{name} must be saved' if value.new_record?
      old_value = self.#{name}
      parents.destroy(old_value) if old_value.present?
      AssetLink.create_edge!(value, self)
    end

    def has_#{name}?
      #{name}.present?
    end
  ",
    __FILE__,
    line
  )
end