Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The reason why your code is not working is simple - you are working with @content which is <code>nil</code> in the context of execution (the <code>self</code> is the class, not the instance). So you are basically modifying eigenclass of nil.</p> <p>So you need to extend the instance of @content when it's set. There are few ways, there is one:</p> <pre><code>class HtmlSnippet &lt; ActiveRecord::Base # getter is overrided to extend behaviour of freshly loaded values def content value = read_attribute(:content) decorate_it(value) unless value.respond_to?(:replace_url_to_anchor_tag) value end def content=(value) dup_value = value.dup decorate_it(dup_value) write_attribute(:content, dup_value) end private def decorate_it(value) class &lt;&lt; value def replace_url_to_anchor_tag # ... end end end end </code></pre> <p>For the sake of simplicity I've ommited the "nil scenario" - you should handle <code>nil</code> values differently. But that's quite simple.</p> <p>Another thing is that you might ask is why I use <code>dup</code> in the setter. If there is no <code>dup</code> in the code, the behaviour of the following code might be wrong (obviously it depends on your requirements):</p> <pre><code>x = "something" s = HtmlSnippet.find(1) s.content = x s.content.replace_url_to_anchor_tag # that's ok x.content.replace_url_to_anchor_tag # that's not ok </code></pre> <p>Wihtout <code>dup</code> you are extending not only x.content but also original string that you've assigned.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload