Thursday, February 3, 2011

How to turn a string into CamelCase in Ruby


Below are the few tricks to capitalize only the first letter of each word of a multi word string.
def wikify(phrase)
phrase.gsub!(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
phrase.gsub!(/\s/, '')
return phrase
end
This turns “my dog has fleas” into “MyDogHasFleas”.


If you’re in Rails, you can take advantage of the Inflector class and do something like this:
>> phrase = ‘my Dog hAs FlEas’
=> “my Dog hAs FlEas”
>> phrase.downcase.gsub(/\s/, ‘_’).camelize
=> “MyDogHasFleas”
I only know this because the inflector’s “titleize” method is great if you want to “capitalize” multi-word phrases.


def wikify(phrase)
phrase.downcase.gsub(/\b[a-z]/) { |a| a.upcase }.gsub(/\s/, ”)
end

  'some string here'.gsub(/\b\w/){$&.upcase}
>> Some String Here

Sunday, January 30, 2011

convert string to Time rails


How can I convert a string such as '2007-01-31 12:22:26' to a Time
object?
irb(main):001:0> require 'time'
=> true
irb(main):002:0> Time.parse('2007-01-31 12:22:26')
=> Wed Jan 31 12:22:26 EST 2007
Chronic can do that and a whole lot more (in case you need to)!

require 'chronic'

Chronic.parse('2007-01-31 12:22:26')
=> Wed Jan 31 12:22:26 -0800 2007

Chronic.parse('today at 12:22.26')
=> Wed Jan 31 12:22:26 -0800 2007

Fixing invalid UTF-8 in Ruby


When working with UTF-8-encoded text from an untrusted source like a web form, it’s a good idea to fix any invalid byte sequences at the first stage, to avoid breaking later processing steps that depend on valid input.
For a long while, the Ruby idiom that I’ve been using and recommending to others is this:
ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')
valid_string = ic.iconv(untrusted_string)
IGNORE is supposed to tell the processor to silently discard bytes that it can’t convert. The output thus contains only valid byte sequences from the input—exactly what we want.
Today, quite by accident, I discovered a problem with it. Iconv in all its forms (library and command-line, on Linux and on Mac OS X) will ignore invalid byte sequences unless they occur right at the end of the string; compare this:
ic.iconv("foo303bar") # => "foobar"
and this:
ic.iconv("foo303") # Iconv::InvalidCharacter: "303"
What’s more, it’s only a certain range of bytes that break the conversion:
(128..255).inject([]){ |acc, b|
begin
ic.iconv("foo%c" % b)
acc
rescue
acc << b
end
}
The ‘dangerous’ bytes are those in the range 194-253. To put it another way, that’s all bytes of the binary pattern /^1{2,6}0/—the leading bytes from a UTF-8 byte sequence. (Incidentally, it’s interesting to see that, at least on OS X, it recognises the never-used and since-withdrawn five- and six-byte sequences from the original UTF-8 specification).
All of this is useful in explaining why it happens, but not how to fix it. The fix, however, is simple:
ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')
valid_string = ic.iconv(untrusted_string + ' ')[0..-2]
Add a valid byte before converting, and remove it afterwards, and voilĂ —there’s never an invalid sequence at the end of the buffer. (It’s possible to improve the efficiency of this implementation if you don’t care about preserving the original string: use << instead of + to add the space.)
As to why //IGNORE doesn’t ignore this situation, I don’t know. As far as I can tell, the POSIX specification doesn’t specifically address the //IGNORE flag, so it’s hard to say what it should be doing.





http://po-ru.com/diary/fixing-invalid-utf-8-in-ruby-revisited/

Ruby: convert string to date


Date.strptime("{ 2009, 4, 15 }", "{ %Y, %m, %d }")
http://stackoverflow.com/questions/2720907/ruby-convert-string-to-date

Convert to/from DateTime and Time in Ruby

require 'time'
require 'date'

t = Time.now
d = DateTime.now

dd = DateTime.parse(t.to_s)
tt = Time.parse(d.to_s)


http://stackoverflow.com/questions/279769/convert-to-from-datetime-and-time-in-ruby

Monday, January 24, 2011

generate a random string in rails

1:
o = [('a'..'z'),('A'..'Z')].map{|i| i.to_a}.flatten;
string = (0..50).map{ o[rand(o.length)] }.join;




2:
Why not use SecureRandom, provided by ActiveSupport?
require 'active_support/secure_random'
random_string = ActiveSupport::SecureRandom.hex(16)
# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81
SecureRandom also has methods for:
base64
hex
random_bytes
random_number
see: http://api.rubyonrails.org/classes/ActiveSupport/SecureRandom.html



3:
This solution generates a string of easily readable characters for activation codes; I didn't want people confusing 8 with B, 1 with I, 0 with O, etc.

# Generates a random string from a set of easily readable characters
def generate_activation_code(size = 6)
charset = %w{ 2 3 4 6 7 9 A C D E F G H J K L M N P Q R T V W X Y Z}
(0...size).map{ charset.to_a[rand(charset.size)] }.join
end


4:
Can't remember where I found this, but seemed the best to me and least process intense:

def random_string(length=10)
chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
password = ''
length.times { password << chars[rand(chars.size)] }
password
end



5:
`pwgen 8 1`.chomp



6:
I use this for generating random url friendly strings.

rand(32**length).to_s(32)
It generates random strings of lowercase a-z and 0-9. It's not very customizable but it's short and clean.


7:
Another method I like to use

rand(2**256).to_s(36)[0..7]
Add ljust if you are really paranoid about the correct string length:

rand(2**256).to_s(36).ljust(8,'a')[0..7]




8:
To make your first into one statement:

(0...8).collect { |n| value << (65 + rand(25)).chr }.join()




9:
With this method you can pass in an abitrary length. It's set as a default as 6.

def generate_random_string(length=6)
string = ""
chars = ("A".."Z").to_a
length.times do
string << chars[rand(chars.length-1)]
end
string
end



10:
ALPHABET = ('a'..'z').to_a
10.times.map{ ALPHABET.sample }.join
10.times.inject(''){|s| s << ALPHABET.sample }





11:

RFC-822 date-time format

Here are examples of valid RFC822 date-times:

Wed, 02 Oct 2002 08:00:00 EST

Wed, 02 Oct 2002 13:00:00 GMT

Wed, 02 Oct 2002 15:00:00 +0200