All threads / Model/concerns question

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Model/concerns question

Dave Castellano asked in Rails

Hi. I am learning ROR on my own (no formal programming trainng) so this may be a question with an obvious answer but i'm stuck and the answer will help me understand how to call concerns. I have a method I want to use in several models - capitalize_it.
In app/models/concerns/capitalize_it:
module CapitalizeIt
extend ActiveSupport::Concern

module ClassMethods
def capitalize_title(title) # Capitalizes multi-word titles.
cap_stop_words = %w(for and the of to at is a)
title.capitalize!
n = 0
title = title.split(" ").collect{ |word|
if n == 0
n=n+1
word.capitalize
else
cap_stop_words.include?(word) ? word : word.capitalize
end
}.join(" ")
end
end
end

In model: Have tried several ways to pass the title arguement to the module... to no avail!
class Subject < ActiveRecord::Base
include CapitalizeIt
def name
self.title
end
capitalize_title(name)

Great topic for me to record a screencast on.

Modules really just add methods to a class, so you can define both class and instance methods in the module and they're accessible as if they were defined in the class.

The module in your example adds an instance method, so you could call it inside any method in your class.

class Subject < ActiveRecord::Base
  include CapitalizeIt
  def name
    capitalize_title(self.title)
  end
end

If you were to add a class method in the module, then you could call it outside of a method because code that runs there is running inside the class, not an instance.

Methods like scope belongs_to and has_many are all examples of class methods.

Thank you Chris. A screencast would be great!

There are no longer any error messages but the associated index.html.erb view outputs uncapitalized. When i put "debugger" inside:

class Subject < ActiveRecord::Base
include CapitalizeIt
def name
debugger
capitalize_title(self.title)
end
end

It is not seen and debugger is not activated

And your view is calling <%= @subject.name %>?

If you're calling title directly, then you're not calling your capitalize_title method. You would want to call the name method.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 35,699+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.