creating name helper, to split first and last name

2020-04-04 12:57发布

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!

8条回答
淡お忘
2楼-- · 2020-04-04 13:49

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.

class String
  def given; self.split(' ').first end
  def surname; self.split(' ').last end
end

"Phileas Fog".surname # 'fog'

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.

class ProperName < String
  def given; self.split(' ').first end
  def surname; self.split(' ').last end
end

class User
  def name
    ProperName.new(self.read_attribute(:name))
  end
end

u = User.new(:name => 'Phileas Fog')
u.name # 'Phileas Fog'
u.name.given # 'Phileas'
u.name.surname # 'Fog'
查看更多
Bombasti
3楼-- · 2020-04-04 13:49

Just as complement of great Dave Newton's answer, here is what would be the "last name" version:

  def last_name
    self.full_name.blank? ? "" : self.full_name.split(" ")[-1]
  end
查看更多
登录 后发表回答