I want to replace apostrophe(') in a name with "backslash apostrophe" (\') . But Unfortunately not getting such a simple thing.
So on irb I tried following
x = "stack's"
x.gsub(/[\']/,"\'")
Some how it is not working I am getting same result- stack's in place of stack\'s
Try this:
x = "anupam's"; puts x.gsub("'", "\\\\'")
Try this out:
x.gsub(/[']/,"\\\\\'")
Result:
1.9.3p0 :014 > puts x.gsub(/[']/,"\\\\\'")
anupam\'s
Here's a ruby variant for PHPs addslashes method (from http://www.ruby-forum.com/topic/113067#263640). This method also escapes \ in the string, with double \:
class String
def addslashes
self.gsub(/['"\\\x0]/,'\\\\\0')
end
end
Which would correctly escape anupam's:
"anupam's".addslashes # => "anupam\\'s"
Related
All integers are by default delimited by ',' .
For ex: 123456 is shown as 1,23,456.
Is there a way to remove ',' from all integers for all tables.
If it is for a single table and a particular field, we can do in the following way in its controller.
config.columns[:<int_field>].options={:i18n_options => {delimiter: ""}}
Is there a way to do this for all integer fields?
PS: Using Activescaffolding in my application.
Thanks.
Use tr as:-
2.0.0-p645 :005 > "1,23,456".tr(',', '')
=> "123456"
Convert the result to integer as:-
2.0.0-p645 :005 > "1,23,456".tr(',', '').to_i
=> 123456
Check methods in string in irb as:-
"".methods
Use it in view as:-
<%= "1,23,456".tr(',', '').to_i %>
For more details see the document
I assume Rails with Activescaffold uses formatting rules from its I18n module by default. You can change them in config/locales/en-US.yml. Here is the default one with the relevant lines highlighted.
This should affect all formatting of numbers in views. I think you just have to change the delimiter to a blank string:
...
format:
delimiter: ""
...
You can find general information about Rails I18n in the corresponding I18n guide.
This worked perfectly.
Added the following lines in application_helper.rb:
def format_number_value(value, delimiter = '')
if value.is_a? Integer
ActiveSupport::NumberHelper.number_to_delimited(value, delimiter: '')
else
super
end
end
Thanks.
In my Rails application I have a field address which is a varchar(255) in my SQLite database.
Yet whenever I save an address consisting of more than one line through a textarea form field, one mysterious whitespace character gets added to the right.
This becomes visible only when the address is right aligned (like e.g. on a letterhead).
Can anybody tell me why this is happening and how it can be prevented?
I am not doing anything special with those addresses in my model.
I already added this attribute writer to my model but it won't remove the whitespace unfortunately:
def address=(a)
write_attribute(:address, a.strip)
end
This is a screenshot:
As you can see only the last line is right aligned. All others contain one character of whitespace at the end.
Edit:
This would be the HTML output from my (Safari) console:
<p>
"John Doe "<br>
"123 Main Street "<br>
"Eggham "<br>
"United Kingdom"<br>
</p>
I don't even know why it's putting the quotes around each line... Maybe that's part of the solution?
I believe textarea is returning CR/LF for line separators and you're seeing one of these characters displayed between each line. See PHP displays \r\n characters when echoed in Textarea for some discussion of this. There are probably better questions out there as well.
You can strip out the whitespace at the start and end of each line. Here are two simple techniques to do that:
# Using simple ruby
def address=(a)
a = a.lines.map(&:strip).join("\n")
write_attribute(:address, a)
end
# Using a regular expression
def address=(a)
a = a.gsub(/^[ \t]+|[ \t]+$/, "")
write_attribute(:address, a)
end
I solved a very similar kind of problem when I ran into something like this,
(I used squish)
think#think:~/CrawlFish$ irb
1.9.3-p385 :001 > "Im calling squish on a string, in irb".squish
NoMethodError: undefined method `squish' for "Im calling squish on a string, in irb":String
from (irb):1
from /home/think/.rvm/rubies/ruby-1.9.3-p385/bin/irb:16:in `<main>'
That proves, there is no squish in irb(ruby)
But rails has squish and squish!(you should know the difference that bang(!) makes)
think#think:~/CrawlFish$ rails console
Loading development environment (Rails 3.2.12)
1.9.3-p385 :001 > str = "Here i am\n \t \n \n, its a new world \t \t \n, its a \n \t new plan\n \r \r,do you like \r \t it?\r"
=> "Here i am\n \t \n \n, its a new world \t \t \n, its a \n \t new plan\n \r \r,do you like \r \t it?\r"
1.9.3-p385 :002 > out = str.squish
=> "Here i am , its a new world , its a new plan ,do you like it?"
1.9.3-p385 :003 > puts out
Here i am , its a new world , its a new plan ,do you like it?
=> nil
1.9.3-p385 :004 >
Take a loot at strip! method
>> #title = "abc"
=> "abc"
>> #title.strip!
=> nil
>> #title
=> "abc"
>> #title = " abc "
=> " abc "
>> #title.strip!
=> "abc"
>> #title
=> "abc"
source
What's the screen shot look like when you do:
def address=(a)
write_attribute(:address, a.strip.unpack("C*").join('-') )
end
Update based on comment answers. Another way to get rid of the \r's at the end of each line:
def address=(a)
a = a.strip.split(/\r\n/).join("\n")
write_attribute(:address, a)
end
When I have a list of hashes, like the result of an .attributes call, what is a short way to create a line-by-line nicely readable output?
Like a shortcut for
u.attributes.each {|p| puts p[0].to_s + ": " + p[1].to_s}
I'm not sure you can make it much shorter unless you create your own method.
A minor enhancement would be:
u.attributes.each {|k,v| puts "#{k}: #{v}"}
Or you can create an extension to Hash:
class Hash
def nice_print
each {|k,v| puts "#{k}: #{v}"}
end
end
u.attributes.nice_print
AS said in my comments, I like to use y hash or puts YAML.dump(hash) that shows your hash in yaml. It can be used for other objects too.
h = {:a => 1, :b => 2, :c => 3}
# => {:a=>1, :b=>2, :c=>3}
y h
#---
#:a: 1
#:b: 2
#:c: 3
# => nil
There is also an informative answer about it.
If you are looking for an output for development purposes (in Rails log files for instance), inspect or pretty_inspect should do it :
u.attributes.inspect
or
u.attributes.pretty_inspect
But if what you are looking for is a way to print nicely in Rails console, I believe you will have to write your own method, or use a gem like awesome_print, see : Ruby on Rails: pretty print for variable.hash_set.inspect ... is there a way to pretty print .inpsect in the console?
awesome_print is the way to go
gem install awesome_print
require "ap"
ap u.attributes
I came across something that seems unusual and I was wondering if anyone could explain why.
1.8.7 :001 > some_str = "Hello World"
=> "Hello World"
1.8.7 :002 > some_str.try(:match, /^(\w*)/)
=> #<MatchData "Hello" 1:"Hello">
1.8.7 :003 > $1
=> nil
1.8.7 :004 > some_str.match(/^(\w*)/)
=> #<MatchData "Hello" 1:"Hello">
1.8.7 :005 > $1
=> "Hello"
I'm not sure why the global variable $1 is not being set the first time, but is set the second. Any insights?
Let me show you how try is implemented. If you want to see it yourself, then take a look at the activesupport source. It's defined in /lib/active_support/core_ext/object/try.rb
class Object
def try(*a, &b)
if a.empty? && block_given?
yield self
else
public_send(*a, &b)
end
end
end
What this basically does, is just sending the method name and the complete arguments to the Object. public_send is the same as send, but can only be used to call public methods.
So I rewrote this, to debug your issue:
class Object
def try(*a)
result = public_send(*a)
puts $1.inspect
result
end
end
string = "Hello"
string.try(:match, /^(\w*)/)
puts $1.inspect
This outputs
"Hello"
nil
So the great question arises: Is this a bug in the ruby interpreter?. Maybe. At least it's not documented in any official source. I found a reference that tells the following (See Global variables.)
[...], $_ and $~ have local scope. Their names suggest they should be global, but they are much more useful this way, and there are historical reasons for using these names.
So it seems like $1 is not a global variable as well, even though it is reported by the Kernel as a global variable:
1.9.3-p194 :001 > global_variables
=> [:$;, :$-F, :$#, :$!, :$SAFE, :$~, :$&, :$`, :$', :$+, :$=, :$KCODE, :$-K,
:$,, :$/, :$-0, :$\, :$_, :$stdin, :$stdout, :$stderr, :$>, :$<, :$.,
:$FILENAME, :$-i, :$*, :$?, :$$, :$:, :$-I, :$LOAD_PATH, :$",
:$LOADED_FEATURES, :$VERBOSE, :$-v, :$-w, :$-W, :$DEBUG, :$-d, :$0,
:$PROGRAM_NAME, :$-p, :$-l, :$-a, :$binding, :$1, :$2, :$3, :$4, :$5, :$6,
:$7, :$8, :$9]
To make sure, I forwarded this incosistency to the Ruby Bug Tracker. See Ruby Bug #6723
try is defined as
def try(method, *args, &block)
send(method, *args, &block)
end
except of course on nil where it just returns nil. Why does this matter? Because the regexp globals aren't real globals: they're maintained on a per method and per thread basis (it's easy enough to see this by perusing the ruby source). When you call match via try the globals are set in the scope for try but in the next case they are set at the top level. It's easy to verify this
def do_match string, regexp
string =~ regexp
$1
end
do_match "Hello World", /^(\w*)/ #=> returns 'Hello'
$1 #=> returns nil
ActiveSupport offers the nice method to_sentence. Thus,
require 'active_support'
[1,2,3].to_sentence # gives "1, 2, and 3"
[1,2,3].to_sentence(:last_word_connector => ' and ') # gives "1, 2 and 3"
it's good that you can change the last word connector, because I prefer not to have the extra comma. but it takes so much extra text: 44 characters instead of 11!
the question: what's the most ruby-like way to change the default value of :last_word_connector to ' and '?
Well, it's localizable so you could just specify a default 'en' value of ' and ' for support.array.last_word_connector
See:
from: conversion.rb
def to_sentence(options = {})
...
default_last_word_connector = I18n.translate(:'support.array.last_word_connector', :locale => options[:locale])
...
end
Step by step guide:
First, Create a rails project
rails i18n
Next, edit your en.yml file: vim config/locales/en.yml
en:
support:
array:
last_word_connector: " and "
Finally, it works:
Loading development environment (Rails 2.3.3)
>> [1,2,3].to_sentence
=> "1, 2 and 3"
As an answer to how to override a method in general, a post here gives a nice way of doing it. It doesn't suffer from the same problems as the alias technique, as there isn't a leftover "old" method.
Here how you could use that technique with your original problem (tested with ruby 1.9)
class Array
old_to_sentence = instance_method(:to_sentence)
define_method(:to_sentence) { |options = {}|
options[:last_word_connector] ||= " and "
old_to_sentence.bind(self).call(options)
}
end
You might also want read up on UnboundMethod if the above code is confusing. Note that old_to_sentence goes out of scope after the end statement, so it isn't a problem for future uses of Array.
class Array
alias_method :old_to_sentence, :to_sentence
def to_sentence(args={})
a = {:last_word_connector => ' and '}
a.update(args) if args
old_to_sentence(a)
end
end