Rob On Rails

My little weblog about learning Ruby and Rails.

Adding markdown to your project

A quick one this time. I’ve just gone about implementing the following setup, which is a super easy way to add Markdown support in your views (and, well, anywhere).

We’ll be using the RDiscount gem for this. There are other gems like Bluecloth, but RDiscount has been consistently good for a long time now.

config/environment.rb add:

config.gem "rdiscount"

then install the new gem using “sudo rake:gems install” and restart rails…

…and that’s it. Now you can parse markdown into html like this:

RDiscount.new("My Lovely Markdown").to_html

But, that’s a mouthful and doesn’t look very clean in a view. So, what I did instead was to open up the String class and add a method called markdown which does that for us.

The easiest way to do that and make it available everywhere is to make an initializer.

Make the file “markdown.rb” in config/initializers/ and fill it with:

class String
  def markdown
    RDiscount.new(self).to_html
  end
end

After restarting rails, you will be able to convert markdown like this:

"My String".markdown

Now isn’t that special?

Validating images with Paperclip

If you don’t already use it, check out Thoughtbot’s Paperclip first.

Doing this is always a huge pain, so I wrote a mixin which makes it super easy. It’s based upon some model code I referenced online before, but with a crucial bug fix relating to a situation where an exception would be raised if you posted a form without selecting an image.

So, without further ado:

validates_as_image

module ValidatesAsImage

  def self.included receiver
    receiver.extend ClassMethods
  end

  module ClassMethods
    def validates_as_image fields

      validates_each fields do |record, attr, value|
        if !value.queued_for_write.empty? and value.to_file
          `identify "#{value.to_file.path}"`
          record.errors.add attr, 'is not a valid image' unless $? == 0
        end
      end
         
    end
  end
  
end

Requires Imagemagick to be installed on your server, and the ‘identify’ command must be in your path. Paste this code into a file in your lib folder and restart the server.

Here’s an example of how to use it:

class Widget < ActiveRecord::Base
  
  include ValidatesAsImage
  
  has_attached_file :photo,
                    :whiny => false,
                    :styles => {  :medium  =>  { :geometry => '300x300#', :format => "png" },
                                      :thumb => { :geometry => '100x100#', :format => "png" } }  
  
  validates_as_image :photo

  def etc
     #.........
  end
end

Note that I have turned the :whiny option on in Paperclip. It’s not strictly necessary, but if it’s on you will get extra, redundant form validation errors, as well as just “Photo is not a valid image.” See the documentation for the whiny option here: has_attached_file.

Happy camping.

Damn

The itegration between Rails and (I hate to say it) AJAX is really awesome.

I’ve created something that would take an afternoon to make in PHP in about 2 minutes.

Wow.

MacRuby

This looks interesting [Apple.com]

Develop OS X-native apps with Ruby + Cocoa bindings? Sweet.

Another Challenge

Okay, so I found another challenge I could do, this time on RosettaCode which deals with file I/O in Ruby.

Basically, there’s a 10,000 line log file to parse and gather some data from it.

This one was really, really simple and took about 5 minutes to do.

license_out = 0
record_out = 0
record_times = []
File.open("licenselog.txt").each do |line|
	if line.include?("OUT")
		license_out += 1
	else
		license_out -= 1
	end
	
	if license_out > record_out
		record_out = license_out
		record_times << line.split(" ")[3]
	end
end

puts "Maximum licenses out: #{record_out} at the following times: "
puts record_times.join("\n")

Yield!

Wow, this is cool:

def test_block
	puts "Beginning...."
	yield if block_given?
	yield if block_given?
	puts "Ended!"
end

test_block do
	puts "I am being called from within test_block!"
end

More Euler..

Just finished Project 4.

This isn’t the most concice code, because i functionised it, but it works quite well.

class Numeric
	def is_palindrome?
		s_num = self.to_s
		half = s_num[0..(s_num.length/2)-1].to_s
		s_num == half + half.reverse or
			(s_num.length%2 == 1 and s_num == half + s_num[s_num.length/2,1].to_s + half.reverse)
	end
end


def find_largest_palindrome number_digits

	highest_number = (9.to_s * number_digits).to_i
	lowest_number = (1.to_s + 0.to_s* (number_digits - 1)).to_i
	
	largest = 0
	largest_sqrt = 0

	highest_number.downto(lowest_number).each do |num1|
		highest_number.downto(num1).each do |num2|
			if largest_sqrt * 2 > num1 + num2
				break
			end
		
			if (num1 * num2).is_palindrome? and num1 * num2 > largest
				largest = num1 * num2
				largest_sqrt = Math.sqrt(largest)
			end
		end		
	end
	largest
end

puts "Largest palendrome is #{find_largest_palindrome 3}"

Project Euler

So, I’m gonna do 4 project Euler challenges to get me the hang of this Ruby thing.

Well, get the hang of dealing with numbers, anyway.

I’ve finished the first 3 challenges already, so here you go:

Problem 1

The first challenge is really easy. You have to add the sum of the multiples of 3 and 5 below 1000.

# Establish minimum and maximum
minimum = 1
maximum = 1000

counter = 0
(minimum...maximum).each do |number|
	# Is this a multiple of 3?
	if number%3 == 0 || number%5 == 0
		counter += number
	end
end

puts "The sum of the multiples is: #{counter}"

Problem 2

This problem says you have to add the total of the even numbers in the Fibonacci sequence, up to a maximum of 4 million.

value_1 = 1
value_2 = 0
running_total = 0
# Loop until our fibonacci number is over 4m
until value_1 > 4_000_000 do
	# value_1 + value_2 = current fibonacci sequence number
	value_1 += value_2
	# value_2 = previous fibonacci sequence number, for next time
	value_2 = value_1 - value_2
	# add to the running total if it's an even number
	running_total += value_1 unless (value_1) %2 == 1
end

puts "Total is: #{running_total}"

Problem 3

In this problem, you have to find the largest prime factor of a very high number. This one actually took me the longest to do, as I was doing it manually and discovering its difficult for a non-maths-expert to calculate primes. Then I discovered Ruby could do this for me, making it stupidly easy!

require 'mathn'
puts ARGV[0].to_i.prime_division.last[0]

Hello, world.

Hi everyone. I am a PHP developer with about 5 years experience. I’ve built everything from online stores to forums, but yesterday I realised that all this time I had been fighting PHP to do what I feel it should do naturally. I was spending more time trying to wrangle with the terrible Zend Framework documentation than I was working on the rest of my project. I’d had enough.

Then I remembered Rails. I’d heard about it, investigated it a few times, but never took it seriously. “How can it be this easy?” I thought… and therefore the pessimist in me decided not to persue it, and continue attempting to nail turd to a wall with PHP.

But apparently, there isn’t one. At least, there better not be. Because I read on the internet that there isn’t, and the internet never lies, right…

So, today I started to code in Ruby, and I hope to move onto Rails soon!

I am reading Why’s (Poignant) Guide to Ruby which is both awesome and terrible at the same time. Mostly awesome though. It makes reading documentation fun, which is clearly doing the impossible, so please don’t believe me. It’s a little too wordy though, so I find myself skipping chunks of blurb, only to later be confused about what a Starmonkey is.

My plan is to learn some Ruby with a few exercises, then move onto Rails. Bring it on.

More Information