Single quote string string interpolation - ruby-on-rails

I am trying to set an email address within ActionMailer with Rails. Before it was hard coded, but we want to make them ENV variables now so we don't need to amend code each time an email changes.
Here is how it's currently defined:
from = '"Name of Person" <email#email.com>'
I've tried setting the email as an environment variable using ENV['EMAIL'] but I'm having no luck even with #{ENV['EMAIL'}.
Can anyone point me in the right direction?

You cannot use string interpolation with single-quoted strings in Ruby.
But double-quoted strings can!
from = "'Name of Person' <#{ENV['EMAIL']}>"
But if you want to keep your double-quotes wrapping the Name of Person, you can escape them with a backslash \:
from = "\"Name of Person\" <#{ENV['EMAIL']}>"
Or use string concatenation:
from = '"Name of Person" <' + ENV['EMAIL'] + '>'
# but I find it ugly

If you want to embed double quotes in an interpolated string you can use % notation delimiters (which Ruby stole from Perl), e.g.
from = %|"Name of Person", <#{ENV['EMAIL']}>|
or
from = %("Name of Person", <#{ENV['EMAIL']}>)
Just pick a delimiter after the % that isn't already in your string.

You can also use format. I have not seen it used as commonly in Ruby as in other languages (e.g. C, Python), but it works just as well:
from = format('"Name of Person", <%s>', ENV["EMAIL"])
Alternative syntax using the % operator:
from = '"Name of Person", <%s>' % ENV["EMAIL"]
Here is the documentation for format (aka sprintf):
http://ruby-doc.org/core-2.2.0/Kernel.html#method-i-format

Related

Escape quote in Dart Regex

I'm trying to use the regex /^[a-zA-Z0-9_$&+:;=?##|'<>.^*()%!-]+$/ with dart regex. I've seen you can use raw strings. So Ive put the above in between r'' like this:
r'^[a-zA-Z0-9_$&+:;=?##|'<>.^*()%!-]+$' but the ' is messing it up. How do I tell dart this is a special character..
EDIT
I tried this but it doesn't seem to work
static final RegExp _usernameRegExp = RegExp(
r"^[a-zA-Z0-9_$&+:;=?##|'<>.^*()%!-]+$",
);
So I have a TextField with a text controller for a username. A method like this
static bool isValidUsername(String username) {
return (_usernameRegExp.hasMatch(username));
}
I pass the controller.text as the username.
I've a function:
bool get isUserNameValid => (Validators.isValidUsername(userNameTextController.text.trim()));
I can type all the given characters in to the textbook but not '
Your RegExp source contains ', so you can't use that as string delimiter without allowing escapes. It also contains $ so you want to avoid allowing escapes.
You can use " as delimiter instead, so a raw string like r"...".
However, Dart also has "multi-line strings" which are delimited by """ or '''. They can, but do not have to, contain newlines. You can use those for strings containing both ' and ". That allows r'''...'''.
And you can obviously also use escapes for all characters that mean something in a string literal.
So, for your code, that would be one of:
r'''^[\w&+:;=?##|'<>.^*()%!-]+$'''
r"^[\w&+:;=?##|'<>.^*()%!-]+$"
'^[\\w&+:;=?##|\'<>.^*()%!-]+\$'
(I changed A-Za-z0-9$_ to \w, because that's precisely what \w means).
In practice, I'll always use a raw string for regexps. It's far too easy, and far too dangerous, to forget to escape a backslash, so use one of the first two options.
I'd probably escape the - too, making it [....\-] instead of relying on the position to make it non-significant in the character class. It's a fragile design that breaks if yo add one more character at the end of the character class, instead of adding it before the -. It's less fragile if you escape the -.

How to remove ANSI codes from a string?

I am working on string manipulation using LUA and having trouble with the following problem.
Using this as an example of the original data I am given -
"[0;1;36m(Web): You say, "Text here."[0;37m"
I want to keep the string intact except for removing the ANSI codes.
I have been pointed toward using gsub with the LUA pattern matching but I cannot seem to get the pattern correct. I am also unsure how to reference exactly the escape character sent.
text:gsub("[\27\[([\d\;]+)m]", "")
or
text:gsub("%x%[[%d+;+]m", "")
If successful, all I want to be left with, using the above example, would be:
(Web): You say, "Text here."
Your string example is missing the escape character, ASCII 27.
Here's one way:
s = '\x1b[0;1;36m(Web): You say, "Text here."\x1b[0;37m'
s = s:gsub('\x1b%[%d+;%d+;%d+;%d+;%d+m','')
:gsub('\x1b%[%d+;%d+;%d+;%d+m','')
:gsub('\x1b%[%d+;%d+;%d+m','')
:gsub('\x1b%[%d+;%d+m','')
:gsub('\x1b%[%d+m','')
print(s)

Rails strip all except numbers commas and decimal points

Hi I've been struggling with this for the last hour and am no closer. How exactly do I strip everything except numbers, commas and decimal points from a rails string? The closest I have so far is:-
rate = rate.gsub!(/[^0-9]/i, '')
This strips everything but the numbers. When I try add commas to the expression, everything is getting stripped. I got the aboves from somewhere else and as far as I can gather:
^ = not
Everything to the left of the comma gets replaced by what's in the '' on the right
No idea what the /i does
I'm very new to gsub. Does anyone know of a good tutorial on building expressions?
Thanks
Try:
rate = rate.gsub(/[^0-9,\.]/, '')
Basically, you know the ^ means not when inside the character class brackets [] which you are using, and then you can just add the comma to the list. The decimal needs to be escaped with a backslash because in regular expressions they are a special character that means "match anything".
Also, be aware of whether you are using gsub or gsub!
gsub! has the bang, so it edits the instance of the string you're passing in, rather than returning another one.
So if using gsub! it would be:
rate.gsub!(/[^0-9,\.]/, '')
And rate would be altered.
If you do not want to alter the original variable, then you can use the version without the bang (and assign it to a different var):
cleaned_rate = rate.gsub!(/[^0-9,\.]/, '')
I'd just google for tutorials. I haven't used one. Regexes are a LOT of time and trial and error (and table-flipping).
This is a cool tool to use with a mini cheat-sheet on it for ruby that allows you to quickly edit and test your expression:
http://rubular.com/
You can just add the comma and period in the square-bracketed expression:
rate.gsub(/[^0-9,.]/, '')
You don't need the i for case-insensitivity for numbers and symbols.
There's lots of info on regular expressions, regex, etc. Maybe search for those instead of gsub.
You can use this:
rate = rate.gsub!(/[^0-9\.\,]/g,'')
Also check this out to learn more about regular expressions:
http://www.regexr.com/

How to gsub slash (/) to "" in ruby

To gsub / to "" ruby
I tried as,
ss = "http://url.com/?code=\#{code}"
I am fetching this url from database
then have to gsub \ to '' to pass the dynamic value in code
How to gsub \ to ''
required output
ss = "http://url.com/?code=#{code}"
Your problem is actually not a problem. When you write "http://url.com/?code=\#{code}" in ruby, \# means that ruby is escaping the # character, cause # is a protected character. So you should have the backslash to escape it.
Just to prove this, if you write in a console your string with single quotes (single quotes will escape any special character (but single quotes, of course)):
>> 'http://url.com/?code=#{code}'
=> "http://url.com/?code=\#{code}"
This may be a little obscure but, if you want to evaluate the parameter code in the string, you could do something like this:
>> code = 'my_code'
>> eval("\"http://url.com/?code=\#{code}\"")
=> "http://url.com/?code=my_code"
I believe what you may be asking is "how do I force Ruby to evaluate string interpolation when the interpolation pattern has been escaped?" In that case, you can do this:
eval("\"#{ss}\"")
If this is what you are attempting to do, though, I would highly discourage you. You should not store strings containing the literal characters #{ } in your database fields. Instead, use %s and then sprintf the values into them:
# Stored db value
ss = "http://url.com/?code=%s"
# Replace `%s` with value of `code` variable
result = sprintf(ss, code)
If you only need to know how to remove \ from your string, though, you can represent a \ in a String or Regexp literal by escaping it with another \.
ss.gsub(/\\/,'')
You can try in this way also, working fine for my case.
url = 'www.abc.com?user_id=#{user[:id]}'
uri = URI.parse(url.gsub("=\#", "="))
uri.query = URI.encode_www_form({user_id: 12})
puts uri.to_s ==> "www.abc.com?user_id=12"

Ruby %() vs. ""

I notice some people use %(string here) instead of a simple use of double quotes as "string here". Is there any reason for this? When I use the first layout, I usually make an array such as %w(my array here) so I don't have to use quotes and commas.
Is there a hidden rule I am unaware of? I can't imagine why I would do this:
a = %(some string here)
instead of
b = "some string here"
The latter just seems more clearly written.
They are almost equivalent, using %() you don't have to escape the " character inside the string:
s = %(foo "bar" baz)
# => "foo \"bar\" baz"
They are mostly useful when your string is full of double quotes.
If you're going to have double-quotes embedded within the the string itself, it can be easier to do the %() than to properly escape all of the double-quotes. It may be more readable, too.

Resources