Calling a method from a different class's view

Hi all,

I have two classes: a player class and a game class. Each game has two
player IDs. I would like the game show view to be able to display each
player’s full name via a method, as follows:
<%=h Player.get_player_name(@game.player2) %>

Here is the method definition in my players controller:
def get_player_name(playerID)
@player = Player.find(playerID)
@playerName = @player.firstName + " " + @player.lastName
end

When I try to view the page, I get the error:
Showing app/views/games/show.html.erb where line #8 raised:

undefined method `get_player_name’ for #Class:0x252de68

Extracted source (around line #8):

5:
6:


7: Player2:
8: <%=h Player.get_player_name(@game.player2) %>
9:


10:
11:

I can call the get_player_name method from a player view. Clearly I
don’t understand something about how rails does its scoping, but I am
not sure where to look. For instance, I don’t see anything in my
Learning Rails book that might explain how this works.

My question is: where can I put my get_player_name method so that it
can be accessed by other classes as well?

I am actually surprised that I can’t access the method, because the
following does work from within my game show view:
<%=h Player.find(@game.player1).firstName + " " +
Player.find(@game.player1).lastName %>

Thanks,
Stu

On Mar 18, 10:03 pm, Stu [email protected] wrote:

8: <%=h Player.get_player_name(@game.player2) %>
can be accessed by other classes as well?

This is more of a ruby / object oriented programming fundamentals
question. You say that you defined this method in the players
controller, but you’re attempting to call it as if it was a class
method on Player. If you wanted to make this work then you’d want to
actually make it a class method on Player, ie you would write

def.self.get_player_name(…)

end

in your player class.

That would be slightly odd design though. A more railsy way of doing
it would be for player2 to be an association and to define a full name
method on Player ie

def full_name
firstName + lastName
end

and then your view would look like <%= h @game.player2.full_name %>

It’s also convention that attribute names be underscored (ie
first_name rather than firstName)

Fred

On Mar 18, 5:32 pm, Frederick C. [email protected]
wrote:

It’s also convention that attribute names be underscored (ie
first_name rather than firstName)

The other convention I think is important here is that your “getters”
do not start with “get” like they do in Java. You generally just put
the attribute name. Because Ruby doesn’t require parentheses after
methods, you can just say “player.full_name” instead of
“player.getFullName()” like you would in Java. It’s a more concise and
clear grammar.