Change strings in Rails?
So, I am new to Rails (teaching myself as a senior project in high school) and I am trying to figure out how to change these lines.
Let's say someone writes the following line in the form: "you know you are a geek when"
How can I automatically change it to this: "You know you're a geek when ..."?
I need Rails to check the case of the first letter and check for three dots, then change the string as needed. I've looked here , but I can't find anything that works.
Thank you very much!
EDIT: I'm trying to implement what Ruben Mallaby suggested, but I'm having problems. Here's the relevant part of the lists_controller.rb file, and below is the method in the list.rb model.
def update
@list = List.find(params[:id])
@list.fixlistname
respond_to do |format|
if @list.update_attributes(params[:list])
flash[:notice] = 'List was successfully updated.'
format.html { redirect_to(@list) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @list.errors, :status => :unprocessable_entity }
end
end
end
and..
def fixlistname
new_title = title.humanize + (title.ends_with("...") ? "" : "...")
end
EDIT 2: I want the row to be modified before it enters the database, and this is the error message I am getting:
undefined method `ends_with 'for" You know you're a runner when ": String
GET THIS JOB! THANKS EVERYONE!
a source to share
Just a hint, but when you do "destructive" operations (operations that modify the caller), you must add an exclamation mark (!) To the end of the method name. This is just a convention, but it definitely increases readability and later reduces surprises.
So, in your controller, you will have:
@list.fixlistname!
and in your model you would:
def fixlistname!
new_title = title.humanize + (title.ends_with?("...") ? "" : "...")
end
See here for details .
a source to share
String # capitalize will use the first letter of the string:
"you know you are a geek when".capitalize # => "You know you are a geek when"
And you can get the last three characters of a string using String # [] :
"you know"[-3,3] # => "now"
"you know..."[-3,3] # => "..."
"you know..."[-3,3] == "..." # => true
Rails also provides a nice shortcut for this in the form of String # ends_with? :
"you know...".ends_with?("...") # => true
So, you can check for the end of the line, and if it is not "...", you can add "...":
dots = "..."
my_str = "you know you are a geek when"
my_str = my_str + dots unless my_str.ends_with? dots
# => "you know you are a geek when..."
my_str.capitalize!
puts my_str
# => "You know you are a geek when..."
One edge case that you might want to consider is when the string ends with periods, but not three of them. For example, how would you handle a string like "you know .." (the above method would do it "you know .....") or "you know ....." (the above would leave that unchanged)?
a source to share