Hi, this blog is no longer maintained, my new blog is here

Ruby On Rails and a Conning Israeli entrepreneur

New Design For Pdfetch.com


New design for Pdfetch.com is up, thanks to Barak Edry who did everything to make it look better.
thanks man!

PDFetch released

PDFetch.com was released today by me and Shmuel Ahdut.
PDFetch is a simple app to enable a phrase specific search of online (and free of course) PDF files (other file types will be supported later on).
i will appreciate comments and remarks.

Model Reflection Overview

We all use ActiveRecord Reflection on the fly while programming, since we declare all the relations in the model and we are considering it as obvious.
i tried to search and see if there is a way to find those reflections and to alter it in runtime.

Model.reflections


i found this collection which contains all the information about the current model reflections.
for example.

  • .macro: this will return the type of the current reflection (:has_many, etc..)

  • .primary_key_name: the reflection primary key

  • .options: the reflection SQL join options

  • etc. etc.



for example, the following code will show me all the reflections for a model named Article:

  1. >> y Article.reflections.values.collect {|e| e.macro.to_s  + " => " + e.primary_key_name.to_s }  
  2. ---   
  3. - has_many => taggee_id  
  4. - belongs_to => layout_id  
  5. - has_many => article_id  
  6. - has_one => subject_id  
  7. - belongs_to => user_id  
  8. - has_many => taggee_id  
  9. => nil  

iphone on rails

A simple way to build iPhone specific interface with Rails

  1. class ApplicationController < ActionController::Base  
  2.   exempt_from_layout('iphone_html.erb')  
  3.     
  4.   before_filter :check_iphone  
  5.     
  6.   protected  
  7.   def iphone?  
  8.     request.user_agent.include?('iPhone')  
  9.   end  
  10.     
  11.   def check_iphone  
  12.     if iphone?  
  13.       request.parameters[:format] = 'iphone_html'  
  14.     end  
  15.   end  
  16. end  
  17.   
  18. class DashboardController < ApplicationController  
  19.   def index  
  20.     @top_movies = Movie.top_movies  
  21.     @movie = @top_movies.first  
  22.       
  23.     respond_to do |format|  
  24.       format.html # index.html.erb  
  25.       format.iphone_html #index.iphone_html.erb  
  26.     end  
  27.   end  
  28. end  

The running program

sometimes it can come handy to be able to know in which program you are running know.
it can be useful when displaying error information or such.

  1. caller(0)[0].split(".rb")[0]  >>  "(irb):74:in `irb_binding'"  

WYMeditor - Standards driven WYSIWYG editor

no words are needed, just a small thanks.
thanks for my man Dor Kalev for finding this edgy top of the line XHTML WYSIWYG editor

among the amazing features of this new editor:
1. XHTML strict + CSS compliant

2. No font or text formatting, sizes or colors - WYMeditor is CSS-based Designed

3. to be easy to integrate into your application

4. No installation needed - this is 100% Javascript code - no plugin, no extension

5. Simple Javascript code, you don't need to be a 'Javascript Guru' to understand it

6. Will remain as simple as possible

7. focus on well-tested code, stability and usability before adding new features

8. Image, link, table support

9. Skins supportvia CSS

10. Free and Open Source, fully adaptable to your needs



UPDATED: 13/11/07

The dude released it as a plugin, i am a bit late with this update, but
there it is.

Setting up logger options


i was called the other day about one of my past projects server going down because it's production log exceeded 2GB.
regularly, there is a cron job to cycle the log file and prevent such joyous occasions, but for some reason it didn't happen. so i decided to read a little bit about the Logger class in Rails and see if it has some magic for me yet.



in order to replace the log file path (and/or name) use the following syntax in environment.rb:

  1. Rails::Initializer.run do |config|  
  2.   config.logger = Logger.new(File.dirname(__FILE__) + "/../log/#{RAILS_ENV}.log")  
  3. end  


The actual cure for my problem came when i found the option to prevent the logger file from exceeding a pre-defined limit.
  1. config.logger = Logger.new(File.dirname(__FILE__) + "/../log/#{RAILS_ENV}.log", 1, 2*1024*1024)  


and a little extra for creating a brand new log file for each day.
  1. config.logger = Logger.new(File.dirname(__FILE__) + "/../log/#{RAILS_ENV}.log""daily")  


i suggest reading even more on the rails development browser

Add custom operators in Ruby

Jay Phillips developed the 'superators' gem, which enables the use of custom operators in Ruby. for example.

  1. require 'rubygems'  
  2. require 'superators'  
  3.   
  4. class Array  
  5.   superator "<---" do |operand|  
  6.     self << operand.reverse  
  7.   end  
  8. end  
  9.   
  10. ["jay"] <--- "spillihp"  

relative_time_helper plugin

most of us are using rails's built in time_ago_in_words, Rick Olsan wrote a much better plugin to extend that use and gives much better results.

  1. <%= relative_time(Time.now) %>  
  2. # today  
  3. <%= relative_time(1.day.ago) %>  
  4. # yesterday  
  5. <%= relative_time(1.day.from_now) %>  
  6. # tomorrow  
  7. <%= relative_time_span([Time.now, 5.days.from_now]) %>  
  8. # May 17th - 22nd  


To install it just snap it out of:

  1. script/plugin install http://ar-code.svn.engineyard.com/plugins/relative_time_helpers  

Unique Insertion into Array


  1. [1,2,3] | [3,4,5]       >> [1, 2, 3, 4, 5]  

Seeking Alpha 2.0: Launch successful

After a massive amount of work to do, we all can finally rest for a couple of days (but not too much).

The all new Seeking Alpha site is air-born. i am very proud to be in the technical name list for this one, it is a truly Rails'ish web platform brought to life in the hands of the top israeli ruby on rails aces, and may i add, the best people i had ever had the honour to work with.
so thank you all: Koby "sleepy" Menachemi, Dor "Diet Coke" Kalev, Shmuel l. Unity, Rita "Wacom" Kaplan, Yuval "Float:right;" Raz and the master, Adam "Big Blue" Fine.

way to go guys!

Webistrano - Capistrano deployment the easy way

Blogfish introduced Webistrano, Webistrano is a Web UI for managing Capistrano deployments. It lets you manage projects and their stages like test, production, and staging with different settings. Those stages can then be deployed with Capistrano through Webistrano.



Webistrano's purpose is to make the deployment of multi-stage and multi-environment scenarios easy. Further it allows you to track who deployed what when to which servers and be alerted by email on each deployment.

Webistrano itself is a Ruby on Rails application that includes an edge version of Rails and all needed dependencies like Capistrano or Net::SSH. The only required dependencies are Ruby, Rake, and a database.
Currently the deployment part of Webistrano does not run on Windows.
The code is hosted at Rubyforge and distributed under the BSD license.

Webistrano can be downloaded here

Ruby For bloggers

There are 2 main issues to deal with when posting a technial post on a blog:

1. Syntax Highlighting
There is a wonderful service at The Complex which exports a beautiful Ruby (and other) code, as you see in this blog also.

2. Exampling

You want to example a piece of code you did, how to do it?
try this line:

  1. def show(&block)
  2. printf("%-25s>> %s\n", expr = block.call, eval(expr, block.binding).inspect)
  3. end

for example:
  1. show {%{ a = [1,2,3] }} ; show {%{ a.slice(1,2) }} ; show {%{ a.map { |x| x**3 } }}  

will result in:
  1. a = [1,2,3]                 >>  [1, 2, 3]  
  2. a.slice(1,2)                 >>  [2, 3]  
  3. a.map { |x| x**3 }      >>  [1, 8, 27]  

37 seven reasons to love Ruby

over here

Using your GMail as ActionMailer Carrier

this was merely a try, it worked, but i don't think it's recommended so much, google might get angry.

create a conf file named ssmtp.conf in /etc/ssmtp

  1. # Config file for sSMTP sendmail  
  2. #  
  3. # The person who gets all mail for userids < 1000  
  4. # Make this empty to disable rewriting.  
  5. root=postmaster  
  6.    
  7. # The place where the mail goes. The actual machine name is required no   
  8. # MX records are consulted. Commonly mailhosts are named mail.domain.com  
  9.    
  10. # GMAIL configuration  
  11. mailhub=smtp.gmail.com:587  
  12. AuthUser=youremail@gmail.com  
  13. AuthPass=pass  
  14. UseSTARTTLS=YES  
  15.    
  16. # The full hostname  
  17. hostname=machinehostname  
  18.    
  19. # Are users allowed to set their own From: address?  
  20. # YES - Allow the user to specify their own From: address  
  21. # NO - Use the system generated From: address  
  22. FromLineOverride=YES  


then just point ActionMailer to user sendmail as carrier in your environment:

  1. ActionMailer::Base.delivery_method = :sendmail  


and you are all set

Connection Options

i found a way to get the connection parameters (other than reading database.yml) of the current database connection.

  1. def connection_hash  
  2.   ActiveRecord::Base.connection.instance_variable_get(:@config_options)  
  3. end  

Dynamically adding methods

This is divine, ruby is too great to be true. no explanation needed.


  1. class Object  
  2.   def def(method_name, &block)  
  3.     (class << selfself end).send(:define_method, method_name, block)  
  4.   end  
  5. end  
  6.   
  7. x = Object.new  
  8.   
  9. string = "This is a test"  
  10. x.def(:elad_says) {puts "Elad says: " + string}  
  11.   
  12. x.elad_says  

Routing List

i have seen someone doing this somewhere and i can't remember where. i personally didn't find any use to it, but, you know... someone will.

listing all your routes.

  1. ActionController::Routing::Routes.routes.each do |r|
  2. puts r
  3. end

Mean Mail Machine

i was trying the other day to create some sort of a newsletter. sadly it took me about 2 hours to generate and send 51000 emails (not spam :) ) so i tried to find a way to do it a little faster.
a friend of mine came across the idea of using threads so i tried to override the basics of ActionMailer in order to make the delivery method to user threads.
the change boosted me up to 18-20 mails per second, in other words, 1900% more efficient!
here is the code, just push it in your environment.rb (or lib, whatever), just don't use it for mean/nasty/microsoft needs :).

  1. ActionMailer::Base.delivery_method = :thread_smtp  
  2.   module ActionMailer  
  3.     class Base  
  4.       def perform_delivery_thread_smtp(mail)  
  5.         thread = Thread.new do  
  6.           perform_delivery_smtp(mail)  
  7.         end  
  8.         thread.run   
  9.       end  
  10.   end  
  11. end  

Customize Logger message format

I Hate these long, frustrating long messages coming out on me when i look at the log. They are long, and needed a refreshing change for my opinion.

here is what i found:
There is a method which is responsible for the actual STDOUT printing for the log file, it's called Logger#format_message. I decided to overrun it in a more pretty way.

I created a /lib library called logger_format.rb and required it in environment.rb,

  1. class Logger
  2. def format_message(level, time, progname, msg)
  3. "#{time.to_s(:long)} -- #{msg}\n"
  4. end
  5. end
for example.
try it out and feel free to modify the output structure at will.


get classes of a class

  1. def get_all_subclasses_of(string)
  2. raise ArgumentError.new("#{string} is not an AR Class") if eval(string).class.ancestors
  3. .collect {|e| e.to_s.downcase}.include? ("ActiveRecord::Base")
  4. return ObjectSpace.subclasses_of(eval(string))
  5. end

num_to_english SVN

I am experiencing difficulties with my SVN repository, the plugin will be available on Sunday.

Number to english

num_to_english is my first plugin, i kinda thought it would become a nice addition to the Fixnum class in Ruby.

num_to_english hooks up to the Fixnum class and enables the use of the to_english method as follows

eizesus@eizesus-desktop:~/Projects/testing/trunk$ script/console
Loading development environment.
>> 3.to_english
=> "three"
>> 12.to_english
=> "twelve"
>> 34.to_english
=> "thirty-four"
>> 100.to_english
=> "one hundred"
>> (100 + 321).to_english
=> "four hundred twenty-one"
>> 12312311.to_english
=> "twelve million, three hundred twelve thousand, three hundred eleven"


get it from http://svn.creopolis.com/num_to_english/trunk

counter_cache

Many times when using a belongs_to relation, we encounter the need to size up that association, we can use 2 methods which are created for us, size and (association_pluralization)_count.

so if SuperHero has_many :super_powers than:


me = SuperHero.find(1)
me.super_powers.size
me.super_powers_count


they will both issue that same SQL statement at this point


SELECT count(*) as count_all FROM super_powers WHERE (super_hero_id = 1)

which basically preforms a SELECT * statement, we don't like it :)

the :counter_cache parameter for the belongs_to macro, indicates the use of a
(association_pluralization)_count named column which will be incremented and decremented according to the use of the associative array, this can and does save a lot of time and DB - APP - DB roundup's.



The Chronic files

Although 20.days.ago is a very nice syntax and caused so many non-rails programmers to pass out almost naturally after seeing it work, it still ain't enough.

The Chronic gem enables parsing for date-description strings.
such "yesterday morning" or "sunday next month", Chronic will parse these strings into actual Time objects.

Read more...

Site Mapping

One of the basic elements for each medium sized web-sites and above, is the site map.
when using rails, mapping in not so easy because the object oriented routing which makes it hard to distinct between regular actions and some "maintenance" actions.

I decided to prepare a small library (for now, extensions will be welcomed) which contains 3 basic mapping functions.

The first 2 are pretty custom made for my current project and will be irrelevant for the most of you, but the third is brought to you straight from the oven.

def site_map(path = RAILS_ROOT + "/app/controllers/")
collector = Hash.new
tree = Dir.entries(path).delete_if {|entry| entry.slice(0,1) == "."}
tree = tree.delete_if {|entry| entry.include?('application_controller.rb')}
unless tree.empty?
for element in tree
element = element.gsub('_controller', '')
if element.include?('.rb')
element = element.gsub('.rb', '')
collector['File-' + element] = element.camelize
else
collector['Dir-' + element] = site_map(path + '/' + element)
end
end
end
return collector
end




as you probably noticed, the site_map method returns a Hash.
regular controllers are returned with a key in this format. 'File-', so ClientsController for example will be issued a 'File-Clients' key.
Sub folders will be hashed as well and the same, except that the directory element's key will be in the format of 'Dir-'

Enjoy.

Consult the Console

Day to day life-shortening experiences
My current project is the biggest thing i had ever did, concerning web applications of course (i leave out my origami career).
We have two dedicated servers, 95 models, 45 high powered DRY controllers , a half-operational BackgroundDRb actions, a whole galaxy of multi-asserted tests, test-cases and a functional hell.
A pack of gems, half a dozen plugins and pack of nead to death programmers.
Not that we needed all that for the project, but once you get into a serious programming frenzy, the tendency is to push it as far as you can.

The only thing worrying me was the debugging part, there is nothing in the world more helpless, irresponsible and depraved than a men in the depth of a debugging binge. I noticed that most of my guys aren't using the real powers of the IRB god, and even more, they are not even aware to the hell that can be unleashed when using...

the script/console..


Ok Ok, how?
The console is a simple, command lined interface to your application on any desired environment (specified as a parameter). Using the console you can try your relation in a less pre-defined way then the Testing mechanisem.
simply run script/console in your application root, you will get a very innocent looking command line entry marker, just waiting for you to unleash the beast within... so... why keep it waiting?

Tough love
One thing about the console, it's output is simply readable once used right. Example.

>> first = "i like"
"i like"
>> second = "bananas!"
"bananas!"
>> first + " " + second
"i like bananas!"


gee, this was fun... no?
never mind, the console is primarily used (by me at least) on Models, it enables you to play with your smelly database creatures, without hitting the refresh button on your browser like some kind of a disordered coffee machine... do i smell an example again?

>> elad = SuperHero.find(:first, :conditions => "very_hansom is TRUE")

#"elad", "IQ"=>"7"}>
>> elad.respond_to?(:fly_to) # Just checking if our superhero can fly
true # alright! my very own flying superhero!
>> elad.fly_to("Liverpool") # Mercy-side here i come!
>> elad.location
"Liverpool"

ok, you got the idea.
I Consider myself to be rather a lazy programmer and in fact a person. I found a few other situations where the Rails console might come handy.

Going on a date!

i wanted to check when will one of my packages arrives to it's destination, the nice clerk told me that it will take about 3 weeks before it will get there.
damn, my mathematical skills are weaker even when being compared to my x-ray vision skills. so i immediatly called my favorite problem solver... the console

>> when will my package arrive to destination? # it will never work, just trying :)
SyntaxError: compile error
(irb):1: syntax error, unexpected kWHEN
when will my package arrive to destination?
^
from (irb):1 # Damn :)
>> 3.weeks.from_now
Thu Apr 05 17:54:22 IDT 2007


yippie!, i immediatly called my Samoan clients and to wait for their next gun shipment on april 5th.

Just kidding :), but isn't it beautiful?

The Boolean connection

Few people understand the true mentality of dealing with a Boolean variable.
The normal programmer will panic, and immediately attempt to compare it to a Boolean constant.

when using Rails, This is wrong.

When migrating a boolean typed column using Rails, the actual column type created is "tinyint(1)" (a single digit number presentation which means that the actual value being saved is 0's or 1's.
Where is the problem? in Ruby for a change.
In Ruby, everything except nil and false is considered to a true value. In C, Python and many other languages, 0 and possibly other values, such as empty lists, are considered as false.

which brings us to the inevitable conclusion, that simplay comparing boolean values to true or false will not do.

Rails solves this tiny issue for us, for each boolean attribute, Rails implements a "query method" as i prefer to call them. These query methods are simply called by issuing the boolean attribute name with a "?" suffix.

for example, the @mail_message instance object has a is_important boolean attribute, so instead of doing:


@mail_message.is_important == true

or whatever, we can simply ask rails by:

@mail_message.is_important?


beautiful... isn't it?


The Web Ask eizesus.com

Subscribe

    follow me on Twitter

    Twiters Around

    About Me

    My photo
    I am a web developer for more than 9 years, managed, cried, coded, designed and made money in this industry. now trying to do it again.

    Labels