Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You are asking the difference between a class method and an instance method.</p> <p>There are a few ways of defining a class method:</p> <pre><code>class Klass def Klass.method_name .. end end </code></pre> <p>which is the same as doing:</p> <pre><code>class Klass def self.method_name .. end end </code></pre> <p>or the preferred ruby idiom:</p> <pre><code>class Klass class &lt;&lt; self def method_name .. end end end </code></pre> <p>If Klass is already declared you can also do..</p> <pre><code>def Klass.method_name .. end </code></pre> <p>or: </p> <pre><code>class &lt;&lt; Klass def method_name .. end end </code></pre> <p>or you could even use Module#extend:</p> <pre><code>Klass.extend(Module.new { def method_name; puts 'ducky'; end }) </code></pre> <p>Much like you would add a singleton method to an object. In fact class methods are singleton methods which operate on the class level.</p> <p>In rails ActiveRecord for example you have a class method 'find' which you can use on any Model: </p> <pre><code>Person.find(1) </code></pre> <p>and instance methods like 'save' which operates on the individual object</p> <pre><code>person = Person.find(1) ... person.save </code></pre> <p>In the current project I am working on I have a model Feed which contains data feeds. Periodically I need to run a method which updates all the feeds so i have an fetch_all method which accomplishes this.</p> <pre><code>class Feed &lt; ActiveRecord::Base // class method Feed.fetch_all def self.fetch_all Feed.all.each do |feed| feed.fetch_value end end // instance method def fetch_value // grabs updated value and saves end end </code></pre>
    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.
    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.
    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