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)

Reply

Not solved!

Reply

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.

Reply

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

Reply

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

Reply

<%= @subject.title %>

Reply

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

Reply
Join the discussion
Create an account Log in

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

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

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