Note that there are some explanatory texts on larger screens.

plurals
  1. PORails: Create method available in all views and all models
    primarykey
    data
    text
    <h2>I'd like to define a method that is available in both my <strong>views</strong> and my <strong>models</strong></h2> <p>Say I have a view helper:</p> <pre><code>def foo(s) "hello #{s}" end </code></pre> <p>A view might use the helper like this:</p> <pre><code>&lt;div class="data"&gt;&lt;%= foo(@user.name) %&gt;&lt;/div&gt; </code></pre> <p>However, this <code>&lt;div&gt;</code> will be updated with a repeating ajax call. I'm using a <code>to_json</code> call in a controller returns data like so:</p> <pre><code>render :text =&gt; @item.to_json(:only =&gt; [...], :methods =&gt; [:foo]) </code></pre> <p>This means, that I have to have <code>foo</code> defined in my <code>Item</code> model as well:</p> <pre><code>class Item def foo "hello #{name}" end end </code></pre> <p>It'd be nice if I could have a <strong>DRY</strong> method that could be shared in <em>both</em> my views and my models.</p> <h2>Usage might look like this:</h2> <h3>Helper</h3> <pre><code>def say_hello(s) "hello #{s}" end </code></pre> <h3>User.rb model</h3> <pre><code>def foo say_hello(name) end </code></pre> <h3>Item.rb model</h3> <pre><code>def foo say_hello(label) end </code></pre> <h3>View</h3> <pre><code>&lt;div class="data"&gt;&lt;%= item.foo %&gt;&lt;/div&gt; </code></pre> <h3>Controller</h3> <pre><code>def observe @items = item.find(...) render :text =&gt; @items.to_json(:only=&gt;[...], :methods=&gt;[:foo]) end </code></pre> <p>I don't know the best way to handle this, but I don't want to completely go against best-practices here.</p> <p>If you can think of a better way, I'm eager to learn!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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