↓ Archives ↓

Posts Tagged → ruby

Quick Look at Notepad++ as a Windows Ruby/Rails Editor

Last year, I looked at the better Ruby/Rails editors in Windows. With Notepad++ version 6 released recently, I decided to check whether it’s good enough to be an alternative to those two.

Screenshot again with my depressing lotto app:

notepad++

Overall, it’s ok, especially with the Explorer plugin. However, there are still a bunch of stuff I’d nitpick about:

  • Split screen is limited to 2 screens. Which is weird limitation considering both vim and emacs can do an infinite number of them.
  • EOL symbols are ugly and can’t be modified.
  • No Haml support yet.

This post by Bryan Bibat is from existence, refactored.

Architecture the Lost Years by Robert Martin


This post by Greg Moreno is from Greg Moreno.

More Ruby tips and tricks

String to number conversion gotcha

>> Float('3.14159')
=> 3.14159 
>> '3.14159'.to_f
=> 3.14159 

# However, Float() method will return an exception if given
# a bad input while to_f() will ignore everything from the 
# offending character.

>> Float('3.x14159')
ArgumentError: invalid value for Float(): "3.x14159"
	from (irb):4:in 'Float'
	from (irb):4

>> '3.x14159'.to_f
=> 3.0


# Similar case with to_i() and Integer().

>> Integer('19x69')
ArgumentError: invalid value for Integer(): "19x69"
	from (irb):15:in 'Integer'
	from (irb):15
	from /Users/greg/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in '<main>'

>> '19x69'.to_i
=> 19 

Case insensitive regular expression

# Regex is case sensitive by default. 
# Adding 'i' for insensitive match
puts 'matches' if  /AM/i =~ 'am'

Hash is ordered in 1.9

# new syntax in 1.9
h = {first: 'a', second: 'b', third: 'c'}

# hashes in 1.9 are ordered
h.each do |e|
  pp e
end

Filter a list using several conditions

conditions = [
    proc { |i| i > 5 },
    proc { |i| (i % 2).zero? },
    proc { |i| (i % 3).zero? }
  ]

matches = (1..100).select do |i|
  conditions.all? { |c| c[i] }
end

Randomly pick an element from an array

>> [1,2,3,4,5].sample
=> 2 
>> [1,2,3,4,5].sample
=> 1 

# pick 2 random elements

>> [1,2,3,4,5].sample(2)
=> [1, 5]

List methods unique to a class

# List all instance methods that starts with 're' 
# including those inherited by String.

>> String.instance_methods.grep /^re/
=> [:replace, :reverse, :reverse!, :respond_to?, :respond_to_missing?] 

# List methods unique to String, i.e. not include 
# those defined by its ancestors.

>> String.instance_methods(false).grep /^re/
=> [:replace, :reverse, :reverse!]

Globbing key-value pairs

>> h = Hash['a', 1, 'b', 2]
=> {"a"=>1, "b"=>2}

>> h = Hash[ [ ['a', 1], ['b', 2] ] ] 
=> {"a"=>1, "b"=>2}

>> h = Hash[ 'a' => 1, 'b' => 2 ]
=> {"a"=>1, "b"=>2}

# The first form is very useful for globbing key-value pairs in Rails’ routes. For example, if you have the following:

# route definition in Rails 3
match 'items/*specs' => 'items#specs'

# sample url
http://localhost:3000/items/year/1969/month/7/day/21

# params[:specs] will be set

>> params[:specs]
=> "year/1969/month/7/day/21"

>> h = Hash[*params[:specs].split('/')]
=> {"year"=>"1969", "month"=>"7", "day"=>"21"}


This post by Greg Moreno is from Greg Moreno.

Convert FanFiction.net Stories into PDF

Had a coding itch last week related to web scraping and LaTeX PDF conversion. One thing led to another and the end result was my first ever Ruby Gem:

ffnpdf, a tool that converts FanFiction.net stories into PDF files.

(Great for putting your favorite Harry Potter slash fics on your mobile phone or tablet for portable use! LOL)

The code and documentation are found at the Github page. Theoretically, this gem can work anywhere Ruby, pandoc, and XeTeX can be installed (e.g. Windows, OS X, *nix) but I’ve only been able to make the whole thing work in Ubuntu/Mint.

Demo and how-tos are posted in this playlist:

I haven’t gotten around to make a license for this, but I assume that anyone into fanfiction knows that publishing and selling fanfics without consent from the rights owner is a big no-no. Thus, I don’t need remind them that this tool is just for personal use and not for commercial purposes.

This post by Bryan Bibat is from existence, refactored.

24 Ruby tips and tricks

Peter Cooper will share more tips in his book to be released later this year. Stay tune and don’t forget to leave your email address to get updates at http://rubyreloaded.com/trickshots/

Here are some of the tips in the video.

Generate random numbers within a given range

irb(main):019:0> rand(10..20)
=> 12
irb(main):020:0> rand(10...20) # works with exclusive range
=> 16

Dump your object using awesome_print

# Install the gem first
gem install awesome_print

irb(main):001:0> require 'ap'
=> true
irb(main):002:0> ap :a => 1, :b => 'greg', :c => [1,2,3]
{
    :a => 1,
    :b => "greg",
    :c => [
        [0] 1,
        [1] 2,
        [2] 3
    ]
}
=> {:a=>1, :b=>"greg", :c=>[1, 2, 3]}

Concatenating strings

irb(main):005:0> "abc" + "def"
=> "abcdef"
irb(main):006:0> "abc".concat("def")
=> "abcdef"
irb(main):007:0> x = "abc" "def"
=> "abcdef"

Include modules in a single line

class MyClass
  include Module1, Module2, Module3
  # However, the modules are included in reverse order. Confusing eh!
end

Instance variable interpolation

irb(main):008:0> @name = "greg"
=> "greg"
irb(main):009:0> "my name is #{@name}"
=> "my name is greg"
irb(main):010:0> "my name is #@name"
=> "my name is greg"

I still prefer the use curly braces.

Syntax checking

➜  ruby -c facu.rb 
facu.rb:12: syntax error, unexpected keyword_end, expecting $end

Zipping arrays

irb(main):027:0> names = %w(fred jess john)
=> ["fred", "jess", "john"]
irb(main):028:0> ages = [38, 47,91]
=> [38, 47, 91]
irb(main):029:0> locations = %w(spain france usa)
=> ["spain", "france", "usa"]
irb(main):030:0> names.zip(ages)
=> [["fred", 38], ["jess", 47], ["john", 91]]
irb(main):031:0> names.zip(ages, locations)
=> [["fred", 38, "spain"], ["jess", 47, "france"], ["john", 91, "usa"]]

Range into arrays

irb(main):034:0> (10..20).to_a  # what I used to do
=> [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
irb(main):035:0> [*10..20]
=> [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Using parameter as default value

irb(main):047:0> def method(a, b=a); "#{a} #{b}"; end
=> nil
irb(main):048:0> method 1
=> "1 1"
irb(main):049:0> method 1, 2
=> "1 2"

Put regex match in a variable

irb(main):058:0> s = "Greg Moreno"
=> "Greg Moreno"
irb(main):059:0> /(?<first>\w+) (?<second>\w+)/ =~ s
=> 0
irb(main):060:0> first
=> "Greg"
irb(main):061:0> second
=> "Moreno"


This post by Greg Moreno is from Greg Moreno.

RailsFTW, now twice as fast!

Rails FTW

My Game Jam post is waaay overdue but some stuff happened this week (impromptu upgrade, server migration) so I’ll only get around to post about it probably later today.

Anyway, this post is just about the new version up over at RailsFTW. This experimental build is based on TCS’s patched Ruby build which boasted a ~200% increase in performance.

See it for yourself:

This post by Bryan Bibat is from existence, refactored.

RailsFTW v0.10 released, now with Ruby 1.9.3 and Rails 3.2

Rails FTW

Still hung-over from Global Game Jam 2012 (mini-write-up later) when I went to the RailsInstaller site on a whim.

Noticed that it still isn’t using Rails 3.2. So I decided to update my own to be ahead again.

Hopefully this would be the last RailsFTW version (hoping Luis would be able to convince Wayne to include MySQL to RailsInstaller so I won’t need to this anymore LOL).

This post by Bryan Bibat is from existence, refactored.

Coding Screencasts

I’ve been doing some programming screencasts lately over my Youtube channel. They’re not really “screencasts” ala RailsCasts but more like informal streamed videos that you’d see in Justin.tv/Twitch.tv.

These screencasts were recorded in 720p so it’s a good idea to select a higher resolution then view the videos in full screen or the large player in order for you to read the code properly.

Here I code a hexagonal “game of life”-like cellular automata. Used Ruby, Gosu, and RSpec.

Walking through coding a simple Rails app. Bunch of technologies discussed like Twitter Bootstrap, Heroku, and git.

Going through Project Euler problems via brute force using Java.

This post by Bryan Bibat is from existence, refactored.

RailsFTW v0.9 released, now with Rails 3.1

Rails FTW

Thanks to a Battlefield 3 Beta losing streak that I blame on my sucky internet connection, I’ve decided to update my hack-job of a standalone Windows installer for Rails.

Now there are two separate installers, a Ruby 1.8.7 + Rails 3.0.10 installer and a Ruby 1.9.2 + Rails 3.1.0. Here’s a table to give a quick comparison between these two installers with RailsInstaller thrown into the mix:

  RailsInstaller 2 RailsFTW (Rails 3.1) RailsFTW (Rails 3.0)
Ruby version 1.9.2-p290 1.8.7-p352
Rails version 3.1.0 3.0.10
File Size ~55MB ~20MB ~10MB
DB Adapter Gems sqlite3, pg, tiny_tds (MS SQL Server) sqlite3, mysql2
Additional Features git, DevKit -
Internet Connection Required? Yes No (Bundler will fail to connect to server but new apps will still work) No
Compiled by Some of the biggest names in the Ruby community Some random third world developer. LOL

This post by Bryan Bibat is from existence, refactored.

Illformed requirement Syck::DefaultKey

If you’re getting the errors below, you should update rubygems to the latest, which is 1.8.10 as of this writing.

Installing cucumber-rails (1.0.4) Invalid gemspec in [/Users/crigor/.rvm/gems/ruby-1.9.2-p180@ss/specifications/cucumber-rails-1.0.4.gemspec]: Illformed requirement ["#<Syck::DefaultKey:0x00000100e779e8> 0.7.2"]

Installing database_cleaner (0.6.7) Invalid gemspec in
[/Users/crigor/.rvm/gems/ruby-1.9.2-p180@ss/specifications/cucumber-rails-1.0.4.gemspec]: Illformed requirement ["#<Syck::DefaultKey:0x00000100e779e8> 0.7.2"]

Check out http://blog.rubygems.org/2011/08/31/shaving-the-yaml-yacc.html to get the details. After upgrading rubygems to 1.8.10, I was able to install database_cleaner but I was still getting an error for cucumber-rails. The solution is to open /Users/crigor/.rvm/gems/ruby-1.9.2-p180@ss/specifications/cucumber-rails-1.0.4.gemspec and change

#<Syck::DefaultKey:0x00000100e779e8>

to =. If you’re using vim, just run

:%s/#<Syck.*>/=/

This post by Christopher Rigor is from crigor.com.