Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you create a new model you can make it inherit the methods from an existing class.</p> <p>Example (app/models/mykindofstring.rb):</p> <pre><code>class Mykindofstring &lt; String def all_caps_and_reverse self.upcase.reverse end end </code></pre> <p>Then from the controller:</p> <pre><code>@my_string = Mykindofstring.new('This is my string') </code></pre> <p>and finally calling it from the view:</p> <pre><code>&lt;%= @my_string %&gt; </code></pre> <p>displays as This is my string, while:</p> <pre><code>&lt;%= @my_string.all_caps_and_reverse %&gt; </code></pre> <p>displays as GNIRTS YM SI SIHT.</p> <p>The class inherits from the string class, so all the methods that apply to a string also apply to a mykindofstring object. The method in it is just a new name for a combination of two existing string methods, but you can make it do whatever you want, such as a method to convert a time into a formatted string.</p> <p>Basically it's just extending a current Ruby class with your own methods instead of using functions/helpers.</p> <p><strong>Major Edit</strong></p> <p>Based on Ians comment to this answer and his own answer to the above question, I played around a bit in Rails and came up with adding this to the application_helper.rb:</p> <pre><code>module ApplicationHelper String.class_eval do def all_caps_and_reverse self.upcase.reverse end end end </code></pre> <p>Now just call the method on any string in the app:</p> <pre><code>@string = 'This is a string.' @string.all_caps_and_reverse </code></pre> <p>.gnirts a si sihT</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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