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


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'app/models/asset_link.rb', line 61

def has_one_as_child(name, scope)
  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