before_save, strip a string - ruby-on-rails

I'm trying to strip the whitespaces of the variable Username in my User Model.
I'm using
before_save do
self.username.strip!
end
but it doesn't seem to work, am i missing something ?

You'd rather update the setter instead of polluting your model with callbacks:
def username=(value)
self[:username] = value.to_s.strip
end
Btw, I prefer squish

If you want to remove only leading and trailing white space you can use .strip!
But as you said:
I'm trying to strip the whitespaces of the variable Username in my
User Model.
I think actually you want to remove all spaces following should do:
.gsub(/\s+/, "")
EDIT:
Oh yes, You can also use Rail's built-in method squish()
thanx to apneadiving for reminding

Related

Removing white space from every single input in Rails

Rails 3.2
I am working on an application, where it's important to have leading and trailing white spaces removed, before saving to the DB.
I was planning on writing a helper method, to do:
if !self.attribute_name.nil?
self.attribute_name = self.attribute_name.strip
end
and calling it for every single attribute, in the various models, as a before_save action.
Can you think of simpler way to do this?
There are a lot of gems that handle this for you that I use. One is: github.com/rmm5t/strip_attributes
Then you just include it in each model file instead of every controller for create/update actions
Replacements can be done with the gsub methods. These are substitution methods. gsub applies the substitution globally.
You can use gsub also
if !self.attribute_name.nil?
self.attribute_name = self.attribute_name.gsub(" ", "")
end

Rails to_param - Without ID

I want to create param /users/will-smith, so here's my code:
def to_param
"#{full_name.parameterize}"
end
Parameterize will convert "Will Smith" to "will-smith"
So in the controller, the param won't match the find statement, thus return nil
# User with full_name "will-smith" not found
#user = User.find_by_full_name(params[:id])
Most of the solutions I found is by changing the param to #{id}-#{full_name.parameterize}. But I don't want the URL to contain the ID.
The other solutions is adding permalink column in the database, which I don't really like.
Any other solution?
Thanks
Here's a gem called FriendlyId. It will give you more options to play with.
The problem with your code is that you need to convert that parameter back to original, or use the same kind of transformation on your column during the search. FriendlyId, basically, helps you to achieve the same effect.
Also, I'm not sure, but you could miss that gist. It contaits lots of info on the topic.

gsub within before_validation method is zeroing out my value

I'm trying to remove dollar signs and commas from my form input (for example, $1,000.00 => 1000.00)
I have the following following line in my before_validation method in my model:
self.parents_mortgage = self.parents_mortgage.to_s.gsub!('$,','').to_i
This is causing any number to be put through to zero out. Is there something wrong with my syntax?
use tr:
self.parents_mortgage = self.parents_mortgage.to_s.tr!('$,','').to_i
self.parents_mortgage = self.parents_mortgage.to_s.gsub!('$','').gsub!(',','').to_i
self.parents_mortgage = self.parents_mortgage.to_s.gsub('/[\$,]/','').to_i
Because yes there was a problem with your syntax. Your regex needs the / wrapping, it needs to indicate that $ and , are a character group (by surrounding with []) and you need to escape the $

Helper for removing illegal characters?

I am using a user input string to create a url and I only want the url to contain lowercase letters and hyphens
e.g. example.com/this-is-a-url
In my model, I have added so far:
def to_param
name.downcase.gsub(" ", "-")
end
This makes it lowercase and hyphenated. How can I remove all illegal characters, such as '/"$£%& and so on? A regular expression might be the answer but is there something built in for this purpose already in Rails?
Perhaps instead of doing the above, I should create a validation that makes sure that 'name' is only spaces and letters? Is there something built in for this purpose?
You can use ActiveSupport's parameterize method:
def to_param
name.parameterize
end
parameterize API documentation
You might consider the to_slug plugin for this. See also this related question.

Remove all html tags from attributes in rails

I have a Project model and it has some text attributes, one is summary. I have some projects that have html tags in the summary and I want to convert that to plain text. I have this method that has a regex that will remove all html tags.
def strip_html_comments_on_data
self.attributes.each{|key,value| value.to_s.gsub!(/(<[^>]+>| |\r|\n)/,"")}
end
I also have a before_save filter
before_save :strip_html_comments_on_data
The problem is that the html tags are still there after saving the project. What am I missing?
And, is there a really easy way to have that method called in all the models?
Thanks,
Nicolás Hock Isaza
untested
include ActionView::Helpers::SanitizeHelper
def foo
sanitized_output = sanitize(html_input)
end
where html_input is a string containing HTML tags.
EDIT
You can strip all tags by passing :tags=>[] as an option:
plain_text = sanitize(html_input, :tags=>[])
Although reading the docs I see there is a better method:
plain_text = strip_tags(html_input)
Then make it into a before filter per smotchkiss and you're good to go.
It would be better not to include view helpers in your model. Just use:
HTML::FullSanitizer.new.sanitize(text)
Just use the strip_tags() text helper as mentioned by zetetic
First, the issue here is that Array#each returns the input array regardless of the block contents. A couple people just went over Array#each with me in a question I asked: "Return hash with modified values in Ruby".
Second, Aside from Array#each not really doing what you want it to here, I don't think you should be doing this anyway. Why would you need to run this method over ALL the model's attributes?
Finally, why not keep the HTML input from the users and just use the standard h() helper when outputting it?
# this will output as plain text
<%=h string_with_html %>
This is useful because you can view the database and see the unmodified data exactly as it was entered by the user (if needed). If you really must convert to plain text before saving the value, #zetetic's solution gets you started.
include ActionView::Helpers::SanitizeHelper
class Comment < ActiveRecord::Base
before_save :sanitize_html
protected
def sanitize_html
self.text = sanitize(text)
end
end
Reference Rails' sanitizer directly without using includes.
def text
ActionView::Base.full_sanitizer.sanitize(html).html_safe
end
NOTE: I appended .html_safe to make HTML entities like render correctly. Don't use this if there is a potential for malicious JavaScript injection.
If you want to remove along with html tags, nokogiri can be used
include ActionView::Helpers::SanitizeHelper
def foo
sanitized_output = strip_tags(html_input)
Nokogiri::HTML.fragment(sanitized_output)
end

Resources