Posts tagged ruby

Rails' link_to always gives me a headache

After 9 years of writing Ruby on Rails code, link_to() never ceases to trip me up. Does it trip you up, too? Here are some quick notes:

  1. The first argument is what you want inside the <a> tag. For example link_to("today's news") produces <a>today's news</a>
  2. The second argument is the href attribute value. For example, link_to("today's news", "www.news.com") produces <a href="www.news.com">today's news</a>
  3. The third argument is a hash that contains everything else -- most importantly, your <a> tag attributes. For example, link_to("today's news", "www.news.com", {id: "newsbox", class: "infos"}) produces <a id="newsbox" class="infos" href="www.news.com">today's news</a>. The third argument can contain many other options, of which I have never been able to find a definitive list.

The Ruby on Rails folder structure

When a new Ruby on Rails project is created with rails new, many files and folders are created inside your project folder. Here's a quick reference of what those are.

more...

How to assign a variable based on a condition in Ruby

If you need to assign a variable based on a conditional, most programmers would do something like this:

result = nil
if condition == true
  result = 1
else
  result = 2
end
puts "The result is {result}."

I usually cringe when people say things like, "Oh, that's a very C way of doing that"... but in this case, well, that's a very C way of doing that.

more...

How to list all rake tasks

rake -T -A

This command will print out all available rake tasks. You can use it with Rails' Rakefile, or with a custom Rakefile. N.B.: not all tasks have descriptions, and that is okay.

How to obtain the number of files in a folder, recursively, using Ruby

I have often found myself wanting to know how many files are in a folder, including files in sub-folders. I whipped up a little Ruby code for just that:

folder_to_count = "/path/to/folder"  # You should change this
begin
  file_count = Dir.glob(File.join(folder_to_count, '**', '*')).select { |file| File.file?(file) }.count
rescue
  puts "ERROR: The number of files could not be obtained"
  # typically occurs if folder_to_count does not exist
end

How to make a ruby file executable

In the ruby file:

#!/usr/bin/env ruby
puts 'Hello world'

At the command line:

chmod +x ruby.rb

Then you can execute it like this:

./ruby.rb