Removing white space from every single input in Rails - ruby-on-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

Related

before_save, strip a string

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

How do you store custom constants in Rails 4?

I made some regular expressions for email, bitmessage etc. and put them as constants to
#config/initializers/regexps.rb
REGEXP_EMAIL = /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
REGEXP_BITMESSAGE = /\ABM-[a-zA-Z1-9&&[^OIl]]{32,34}\z/
and use it like
if #user.contact =~ REGEXP_EMAIL
elsif #user.contact =~ REGEXP_BITMESSAGE
Is that's good practice? What's the best way to store them?
It makes sense, that's one of the possible approaches. The only downside of this approach, is that the constants will pollute the global namespace.
The approach that I normally prefer is to define them inside the application namespace.
Assuming your application is called Fooapp, then you already have a Fooapp module defined by Rails (see config/application).
I normally create a fooapp.rb file inside lib like the following
module Fooapp
end
and I drop the constants inside. Also make sure to require it at the bottom of you application.rb file
require 'fooapp'
Lazy-loading of the file will not work in this case, because the Fooapp module is already defined.
When the number of constants become large enough, you can more them into a separate file, for example /lib/fooapp/constants.rb. This last step is just a trivial improvement to group all the constants into one simple place (I tend to use constants a lot to replace magic numbers or for optimization, despite Ruby 2.1 Frozen String literal improvements will probably let me remove several constants).
One more thing. In your case, if the regexp is specific to one model, you can store it inside the model itself and create a model method
class User
REGEXP_EMAIL = /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
REGEXP_BITMESSAGE = /\ABM-[123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ]{32,34}\z/
def contact_is_email?
contact =~ REGEXP_EMAIL
end
end

Globally delimit numbers in rails app?

Is it possible to format all numbers in a rails app to be delimited?
I don't really think this is an i18n issue, as I'm fine with the default delimiter/separator characters. I'm simply trying to avoid putting number_with_delimiter(value) all over my views.
I always want numbers to be displayed as delimited. Always.
So far I've tried extending the Fixnum class with code cribbed from the number_with_delimiter method:
class Fixnum
def delimit(delimiter=",", separator=".")
begin
parts = self.to_s.split('.')
parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}")
parts.join separator
rescue
self
end
end
end
> 98734578.delimit
=> "98,734,578"
> 223.delimit => "223"
So this is a step in the right direction- I like the dot notation as well as the slightly shorter method name. But I'd like to apply this to all instances of a Fixnum inside of a view without having to call .delimit.
Is this a bad idea? Should I be worried about implications this will have on numbers outside of the view context? Is there a better way to accomplish this goal?

Is there any way to define a model's attribute as always html_safe?

I have a model called Feature with a variable called body_string, which contains HTML markup I'd like to render, rather than escape.
Every time I reference body_string in my views, I need to use <%=raw or .html_safe. This seems redundant and not-so-DRY.
Is there any way that I can establish once-and-for-all the body_string variable as html_safe?
I'm assuming this would happen in the app/models/feature.rb file, but I can't figure out what the right syntax would be, exactly. I've thought of this:
def body_string
return self.body_string.html_safe
end
But Rails doesn't like it; it raises a stack level too deep exception.
Naturally I could define a variable/method with a different name:
def safe_body_string
return self.body_string.html_safe
end
And then just change all references in the views from body_string to safe_body_string. But somehow this seems almost as un-DRY as simply using raw or .html_safe in the first place.
Any insights to how best to handle this? I feel like there must be something really elegant that I'm just not seeing.
Just use read_attribute to avoid the recursive call to body_string:
def body_string
read_attribute(:body_string).html_safe
end
read_attribute is complemented by write_attribute for setting attributes from within your model.
A note on style: Don't use explicit returns unless you actually need them. The result of the last statement in a method is implicitly the value returned from the method.
While #meager's answer will definitely work, I don't think this logic belongs in a model. Simply because it adds view-level concerns (HTML safeness) to the model layer, which should just include business logic. Instead, I would recommend using a Presenter for this (see http://nithinbekal.com/posts/rails-presenters/ or find a gem for this -- I personally love Display Case). Your presenter can easily override the body_string method and provide the .html_safe designation when displaying in the view. This way you separate your concerns and can continue to get body_string from other models without mixing in the view concern.
Maybe this gem is useful for you. I also wanted to stop repeating html_safe all the time when the content is completely trustable.
http://rubygems.org/gems/html_safe_attribute
Or you can also use this approach,
def body_string
super && super.html_safe
end

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.

Resources