I'm looking for some help on how to take an attribute and process it through a method to return something different. But I've never done this before and I' not sure where to start. I thought trying to change a name:string attribute from "George Washington" or "John Quincy Adams" into first names only "George" and "John".
I thought maybe a helper method would be best, such as
users_helper.rb
def first_name
end
and then call @user.name.first_name, would this be initially how it would work? Can someone explain where I'd go next to be able to pass @user.name into the method? I've seen things like this but don't quite understand it the parenthesis...
def first_name(name)
puts name
end
Could someone breakdown how rails/ruby does this type of thing? Thanks a lot!
For the syntax you're asking for (
@user.name.first_name
) Rails does a lot of this sort of extension by adding methods to base types, in your example you could do this through defining methods on the String class.Another way to do something like this is to wrap the type you whish to extend, that way you can add all the crazy syntax you wish without polluting more base types like string.
Just as complement of great Dave Newton's answer, here is what would be the "last name" version: