facebook app for newbies
Dorren_mii_thumb by dorren, 3 days ago
very detailed article on how to create facebook app using RoR. very nice, indeed.

found it through google terms: "rails facebook app tutorial"
Views: 12   Replies: 0   Tags: facebook
double your mysql integer column capacity
Dorren_mii_thumb by dorren, 10/05
By default, rails' migration create signed integer columns, which accept both positive and negative values. But in db design, 99% of time integer are used for storing foreign keys. by creating a plugin that override the mysql adapter, all integer column are automatically created with unsigned flag, so you gain twice the id capacity. sweet.

if you do want integer column with negative values, use :signed_int.


module ActiveRecord
  module ConnectionAdapters
    class MysqlAdapter
      # make pk unsigned
      NATIVE_DATABASE_TYPES = {
        :primary_key => "int(11) unsigned DEFAULT NULL auto_increment PRIMARY KEY".freeze,
        :string      => { :name => "varchar", :limit => 255 },
        :text        => { :name => "text" },
        :integer     => { :name => "int", :limit => 4 },
        :signed_int  => { :name => "int", :limit => 4 },
        :float       => { :name => "float" },
        :decimal     => { :name => "decimal" },
        :datetime    => { :name => "datetime" },
        :timestamp   => { :name => "datetime" },
        :time        => { :name => "time" },
        :date        => { :name => "date" },
        :binary      => { :name => "blob" },
        :boolean     => { :name => "tinyint", :limit => 1 }
      }
      
      # Maps logical Rails types to MySQL-specific data types.
      # by default, all integer type are unsigned, unless you use :signed_int in migration.
      #
      # http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html
      def type_to_sql(type, limit = nil, precision = nil, scale = nil)
        return super unless type.to_s == 'integer' or type.to_s == 'signed_int' 

        result = case limit
        when 1; 'tinyint'
        when 2; 'smallint'
        when 3; 'mediumint'
        when nil, 4, 11; 'int(11)'  # compatibility with MySQL default
        when 5..8; 'bigint'
        else raise(ActiveRecordError, "No integer type has byte size #{limit}")
        end
        
        result += " unsigned" unless type.to_s == 'signed_int'
        result
      end      
    end
  end
end
Views: 217   Replies: 0   Tags: mysql
plugin sets relative session expire time
Dorren_mii_thumb by dorren, 07/12
This plugin sets the session cookie expiration in relative time, not fixed time as default rails does, very nice.

Views: 234   Replies: 0   Tags: cookie
Asynchronous Processing (messaging) with Ruby on Rails
Dorren_mii_thumb by dorren, 06/26
meat from slides
  1. General purpose: Bj
  2. Distributed processing: SQS
  3. Speed + scalability: Starling, Workling (workling article)
  4. background-fu

workling's readme pretty much blasted all its alternatives as crap. hehe.

and of course ror's wiki page.
Views: 303   Replies: 0   Tags: messaging
What's new in Rails 2.1
Dorren_mii_thumb by dorren, 06/25
all in this PDF
Views: 391   Replies: 0   Tags: rails
starting with GIT
Dorren_mii_thumb by dorren, 06/19
Git magic, a very comprehensive tutorial, almost like SVN's redbook.
Views: 391   Replies: 0   Tags: git
rails performance development
Dorren_mii_thumb by dorren, 05/20
Ruby on Rails wiki page

tools

articles



Views: 353   Replies: 0   Tags: performance
how to freeze rails
Dorren_mii_thumb by dorren, 03/10
upgrading this app, but there're many other old apps still on rails 1.2.x. so I need to freeze rails for this app. way to do it is to
rake rails:freeze:edge TAG=rel_2-0-2

you can lookup rails edge revision and tag numbers from rails' svn
Views: 579   Replies: 0  
Keeping up with DHH
Dorren_mii_thumb by dorren, 01/01
rails sure evolves fast, now upto version 2.0.2. But I still have boat load of apps running on 1.2.x, spend quite sometime to update all the code and lock down the rails gem version to pre 2, so I can upgrade to latest rails for new apps.

It's sure hard to keep up with DHH.

If you've put "RAILS_GEM_VERSION = '1.2.5' unless defined? RAILS_GEM_VERSION" or frozen rails gem into your old app to 1.2.5 or 1.2.6, and when you run script/server, and get cryptic error like
/usr/lib/ruby/site_ruby/1.8/rubygems.rb:246:in `activate': 
can't activate activesupport (= 2.0.2), already activated activesupport-1.4.4] (Gem::Exception)
Most likely you're missing some gem. run script/console to find the missing gems.

Better solution is to allow your rail apps to define all gems dependencies, and install it automatically.
Views: 658   Replies: 0  
Rails 2 is near
Dorren_mii_thumb by dorren, 11/15/2007
On Nov 9th, David announced the availability of Rails 2 RC 1. Time sure flies.

To see notable features in rails 2, check out RoR blog.
Views: 1048   Replies: 0  
merb is da bomb!
Dorren_mii_thumb by dorren, 11/11/2007
Today I discovered Merb, and it definitely is da bomb class stuff!

What is it? It's a rails like MVC framework without the sucky parts.

The problem with rails is, although convention over configuration is generally a good thing, but sometimes it's hard to draw the line where it is. Merb don't do lots of things for you automatically like rails, so you have the freedom to do things in your own unique way.

Notable features of merbs are:

Pluggable ORM

When you generate a new app, it doesn't assume you're using a DB. so merb can be used to create app without DB need, and server management frontend, cron job admin, etc. Even if you need to use ORM, you have the choice to use activereord, or other ORM I've never heard of, like Datamapper, Sequel.

Manual rendering

Rails' action automatically calls render method for you. This pose some problems, you can't render multiple times or you get double render exception; you can't have nested layout, although people did create nested_layout plugin to work it around.

In merb, you have to call render manually. which just returns the output text as result. want nested layout? then render with different layouts as many times as you want, in situations like you want to provide theme support. As said in ancient Chinese proverb, 进一步,山穷水尽;退一步,海阔天空。(One step forward, you're stuck in nowhere; one step back, there's world of possibilities).

Rails has something similar method called render_to_string, in merb, it's first class citizen.

Plugin dependency

If you've been working with rails for awhile, then you know how much rails plugin suck. There's no plugin dependency, I see people either copy all plugin B code into plugin A if A needs B, or rename plugins since rails loads plugins alphabetically. Note, rails do allow you to configure plugin loading order now.

In merb, plugin is just a gem, multiple versions and dependency are all built in.

Summary

To give credit to rails, merb did "steal" lot of code from rails, but the framwork has vastly different approach. Merb tries to stay agile, a micro framework, yet provides support to allow component builders to add functionality easily.

Merb's tool and coding syntax usage are very similar to rails, so rails developer should be able to learn and use it without much difficulty.

For all rails developers, it's definitely something to dive into.

trivia

One thing intrigues me is that merb is on the domain merbivore.com, not merb.com. After some poking around, then I found out merb.com's owner wanted either $25000 lum sum or $500 monthly rent for use of the domain. No love for open source. :(
Views: 845   Replies: 0   Tags: merb
more problem and hacks in theme_support plugin
Dorren_mii_thumb by dorren, 11/09/2007
Looks like theme_support doesn't work if route ends with an extension, like "/blog/rss.rxml", nor does it work with namespaced action mailer templates. So I had to change the actionview_ex.rb quite a bit to make it to work. here the updated code:

Changes are:
  1. added "../.." for namespaced mailer template
  2. do not pick_template_extension if extension exists in route.
  3. Move __render_file() into try catch block.

Updates, ActionView::TemplateError check

cool, somebody actually read my stuff! well, yes, above hack returns a very bad exception message if you have a error anywhere in ruby code or in rhtml template. Below is the code I should've put up earlier, just never got time to do it. Now here it is.

# Extending ActionView::Base to support rendering themes
#
module ActionView
   
   # Extending ActionView::Base to support rendering themes
   class Base
      alias_method :__render_file, :render_file

      # Overrides the default Base#render_file to allow theme-specific views
      def render_file(template_path, use_full_path = true, local_assigns = {})        
         search_path = [
            # "../themes/#{controller.current_theme}/views/",       # I don't use components
            "../../themes/#{controller.current_theme}/views/",    # for normal views
            "../../themes/#{controller.current_theme}/",          # for layouts
            # "../../../themes/#{controller.current_theme}/views/", # for mailer views, not using now.
            "",                                                   # fallback
            "../",                                                # Mailer fallback
            "../../"                                              # namespaced Mailer fallback
         ]
         
         if use_full_path
            search_path.each do |prefix|
               theme_path = prefix + template_path
               begin
                  template_path_without_extension, template_extension = path_and_extension(theme_path)
                  template_extension = pick_template_extension(theme_path).to_s if !template_extension

                  # Prevent .rhtml (or any other template type) if force_liquid == true
                  if force_liquid? and
                     template_extension.to_s != 'liquid' and 
                     prefix != '.'
                     raise ThemeError.new("Template '#{template_path}' must be a liquid document")
                  end
                  local_assigns['active_theme'] = get_current_theme(local_assigns)
                  return __render_file(theme_path, use_full_path, local_assigns)
               rescue ActionView::TemplateError => err
                   next if err.message =~ /No such file or directory/            # for rxml templates
                   raise err
               rescue ActionView::ActionViewError => err
                   next
               rescue ThemeError => err
                  # Should it raise an exception, or just call 'next' and revert to
                  # the default template?
                  raise err
               end

            end
            raise ActionViewError, "No rhtml, rxml, or delegate template found for #{template_path} in #{@base_path}"
         else
            __render_file(template_path, use_full_path, local_assigns)
         end
      end
      
   private
   
    def force_liquid?
      unless controller.nil?
        if controller.respond_to?('force_liquid_template')
          controller.force_liquid_template
        end
      else
        false
      end
    end

    def get_current_theme(local_assigns)
      unless controller.nil?
        if controller.respond_to?('current_theme')
          return controller.current_theme || false
        end
      end
      # Used with ActionMailers
      if local_assigns.include? :current_theme 
        return local_assigns.delete :current_theme
      end
    end
  end
end
Views: 1203   Replies: 2   Last Reply: dorren, 12/04.     Tags: theme
Add theme support to rails app
Dorren_mii_thumb by dorren, 10/24/2007
If you want to add theme support to your rails app, easiest way is to use Matt McCray's theme_support plugin. just do "script/plugin install http://mattmccray.com/svn/rails/plugins/theme_support/" to get it.

1. The Problem

But it doesn't work out of box. when you start the server, you'll get error like:
theme_app/vendor/plugins/theme_support/lib/patches/routeset_ex.rb:27:in `create_theme_routes': 
undefined method `named_route' for #<actioncontroller::routing::routeset:0xb74da758> (NoMethodError)
        from theme_app/vendor/plugins/theme_support/lib/patches/routeset_ex.rb:13:in `draw'
        from ./script/../config/../config/routes.rb:1
        ...
Since the last update of the plugin was April 2006, and now is Oct 2007, so changes of rails internal must made the plugin incompatible. On Matt's blog, someone suggested a workaround, to change the route function calls in plugin's route patch (lib/patch/routeset_ex.rb). But I choose to take a more conservative approach, not to patch routing at all.

2. The Fix

So here are the changes I made to the plugin to make it futureproof.
  • Disable routing patch. comment out "require 'patches/routeset_ex'" line in theme_support/init.rb
  • Add theme routes into config/routes.rb
    
       map.theme_images "/themes/:theme/images/*filename", :controller=>'theme', :action=>'images'
       map.theme_stylesheets "/themes/:theme/stylesheets/*filename", :controller=>'theme', :action=>'stylesheets'
       map.theme_javascript "/themes/:theme/javascript/*filename", :controller=>'theme', :action=>'javascript'
    
       map.connect "/themes/*whatever", :controller=>'theme', :action=>'error'

Now start the server, and it shall work.

3. Usage

To create a new theme, do "script/generate theme YOUR_THEME_NAME", see plugin's readme for more usage.

4. Related pages

http://code.google.com/p/rails-multisite/
http://wiki.rubyonrails.org/rails/pages/View+Extensions if it's not down.
Views: 927   Replies: 0   Tags: theme
How to config plugin classes in dev/test/prod env file
Dorren_mii_thumb by dorren, 10/02/2007
Most of plugins set initial configuration values in default environment.rb file. What if you've written a plugin, and you want to set different config values in each environment, in RAILS_ROOT/config/environments/XXX.rb? You can't do that directly.

For example, If you have a Widget class in your plugin, and you want to set Widget.param=123 in test.rb, what you get is a big fat class not found error, like
/usr/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/active_support/dependencies.rb:266:in `load_missing_constant': uninitialized constant Widget (NameError)
The reason for that is when rails is starting up and processing each environment file, it hasn't load any plugins yet, so it doesn't know about your plugin classes. When I searched the web for solutions, people tried modifying rails initializer or other similar crazy stuff.

The solution is quite simple, just do it afterwards.

at the end of my environment.rb, just add require File.join(File.dirname(__FILE__), "environments/#{ENV['RAILS_ENV'] || 'test'}_post_init")
"|| 'test'" part is need for rake. then put your plugin configuration code in environments/test_post_init.rb, development_post_init.rb, and production_post_init.rb

If any of the config values are used in config/routes.rb, make sure to copy that line in the beginning of routes.rb file too.

Views: 760   Replies: 0   Tags: plugin
Use Capistrano to deploy your own private gem.
Dorren_mii_thumb by dorren, 09/28/2007
Jeffrey Allan Hardy has written a guide about how to deploy public gems. Now what if you have your own private gems, and you like to deploy them as easily as deploying a rails app, what do you do? Use capistrano. This articles shows how to use Capistrano to deploy your own private gem.

You gem should have existing tasks called "gem" and "install_gem", you can get them automatically if you use new_gem to generate your new gem (that's a mouthful). On another thought, new_gem should be renamed to "gem_gen", sounds alot cooler and less confusing.

1. Write cap tasks

in your gem project folder, create 2 files, "capfile", and "gem_deploy.rb".

capfile should be looks like this:
load 'deploy' if respond_to?(:namespace) # cap2 differentiator load 'gem_deploy'
and gem_deploy.rb should have following
# to deploy this gem, check out first, then # # cap deploy:setup # cap deploy:update_code # # # === reference === # install standard gem # http://www.quotedprintable.com/2007/3/16/installing-gems-with-capistrano #ssh_options[:verbose] = :debug set :synchronous_connect, true # without this, upload task will hang role :lib, "mysite.com" set :application, "my_cool_gem" set :repository, "svn://my/gems/#{application}/trunk" set :deploy_to, "/home/dorren/temp/#{application}" set :user, "dorren" set :deploy_via, :copy namespace :deploy do desc "build and install gem by using rake" task :finalize_update do # -S accepts password from stdin instead of terminal, see man sudo" cmd = "-S ls && cd #{current_release} && rake gem && rake install_gem" sudo cmd do |channel, stream, data| print data if stream == :out channel.send_data($stdin.gets) if data =~ /^>\s/ end end end

2. Deploy

cap deploy:setupwill setup temporary staging folder.
cap deploy:update_code will install the gem.


3. troubleshooting

Q: I get error, "<me> is not in the sudoers file." when deploying.
A: I just added myself into the sudoer group which resolved the problem.
Views: 737   Replies: 0   Tags: capistrano, gem
Same problem, 17 lines in java, 3 lines in ruby
Dorren_mii_thumb by dorren, 09/19/2007
write a program to produce the following output:
1 A
2 BB
3 CCC
......
25 YYYYYYYYYYYYYYYYYYYYYYYYY
26 ZZZZZZZZZZZZZZZZZZZZZZZZZZ
27 012345678901234567890123456

In java, this is probably what most of programmers do:
public class Text { public static void main(String args[]) { int x = 0; for (char c = 'A'; c <= 'Z'; c++) { x++; System.out.print(x + " "); for (int i = 0; i < x; i++) { System.out.print( c ); } System.out.println(); } System.out.print(x + 1 + " "); for (int i = 0; i <= x; i++) { System.out.print(i % 10); } } }

In ruby it only takes 3 lines
n = ?A - 1 (1..26).each do |i| puts i.to_s + " " + (i+n).chr*i end puts "27 " + (0..27).collect{|i| i%10}.to_s

Some rubyism for people not familiar with ruby.
# some ruby language functions # # ?<x> return the ASCII code of the character # ?A => 65 # ?B => 66 # ?\n => 10 backspace ASCII code is 10 # # # <n>.chr returns the character from given ASCII code # 65.chr => "A" # 66.chr => "B" # 10.chr => "\n" # # # <str>*<n> multiplies given string n times. # "ABC"*2 => ABCABC # # # ruby use "#{var}" syntax to print variable in a string # x = "abc" # puts "output: #{x}" => "output: abc"

But you can combine the character and number printing together in one loop. try it.
Views: 791   Replies: 0  
Be_taggable, the commercial ;)
Dorren_mii_thumb by dorren, 09/19/2007
Be_Taggable, the commercial ;)

=== acting troupe actor1 (be): be_taggable, need to be hot and attractive. actor2 (acts): acts_as_taggable, need to be anyone but hot and attractive. === scene 1 acts: Hi, my name is acts_as_taggable. be: Hi, my name is be_taggable. acts: hmmm... never heard of. be: That's ok, I can do what you do, but much easier and efficient. acts: oh yeah? how so? be: my name has only 11 letters, 5 less than yours, a 31.25% improvement. *Acts laugh hysterically* acts: wow, I'm really impressed. be: *unfazed, continues calmly* I have just 67 lines of code, 1/10th of your size. *Acts looking suspiciously at Be for a few seconds* acts: can you tag any models? be: yes, without creating additional join tables. acts: can you find by tags? be: you mean Tag.find_by_name ? yes, you can find by tags, by model class, by count, or any combination of it. *Acts's face gets red* be: plus for model tables, I added tags_cache column to reduce DB traffic. be: Run 3 shell commands will get you started right away, no need to create tables by hand. *Acts faint and fall back onto the ground* be: Did I say too much? *Camera zoom out, blurs* *Display URL http://railers.rubyforge.org/be_taggable *

Many thanks to acts_as_taggable. be_taggable becomes small by standing on the shoulder of acts_as_taggable giant.
Views: 756   Replies: 1   Last Reply: eilson, 09/28/2007.     Tags: be_taggable
Be_taggable plugin, 1/10th size of acts_as_taggable
Dorren_mii_thumb by dorren, 09/18/2007

Meet be_taggable plugin


Originally I planned to use the Acts_as_taggable gem, then i check out the code, and just can't accept how can simple tagging takes 675 lines.

So by "borrowing" code from that gem, I've created be_taggable plugin, major improvements:
  • The name Be_taggable is 5 letters less, or 31.25% more efficient.
  • BeTaggable module weights 67 lines, compare to 675 lines, a whopping 90% improvement.
  • Built in tags_cache column to reduce DB traffic.
  • Simple installation, run 3 commands and you‘re ready to tag and roll.

Install

svn export http://railers.rubyforge.org/svn/plugins/trunk/be_taggable script/generate be_taggable_tables Article Bookmark ... # models to be tagged rake db:migrate

Usage

Class TestBook be_taggable # Mark your class be_taggable. ... end book = TestBook.create(:name => "AWDWR") book.tag("programming, rails") # 2 tags added book.tag("agile, rails") # "programming" removed, "agile" added, "rails" untouched. hash = TestBook.tags_count # {"rails" => 1, "agile" => 1} book.tag("") # remove all tags. TestBook.find_tagged_with("rails") # return list of matching book objects. TestBook.find_tagged_with("rails", :offset => 20, :limit => 10) # search with options.
and in template
# To display model‘s tags from tags_cache column. <% for tag in YAML::load(article.tags_cache) %> <%= link_to(tag, tagged_articles_path(tag)) # assume route exists %> <% end -%> # To show tag cloud <table> <% Article.tags_count.sort.each{|pair| %> <tr> <td><%= link_to(pair[0], tagged_articles_path(pair[0])) %></td> <td><%= pair[1] # count %></td> </tr> <% } %> </table>

Reference

Documentation: http://railers.rubyforge.org/be_taggable/
Code: svn export http://railers.rubyforge.org/svn/plugins/trunk/be_taggable
Views: 704   Replies: 0   Tags: be_taggable, plugin
Simple code for playing card
Dorren_mii_thumb by dorren, 09/15/2007
Simple code to implement playing card. In case you want to build an online casino with Ruby on Rails, you got a head start. :)

class Deck COLOR = %w(S H D C) # Spade Heart Diamond Club POINT = %w(2 3 4 5 6 7 8 9 10 J Q K A) attr_accessor :cards def initialize @cards = [] COLOR.each{|c| POINT.each{|p| @cards << Card.new(COLOR.index(c), POINT.index(p)) } } self end def shuffle 52.times{|i| r = rand(52); @cards[i], @cards[r] = @cards[r], @cards[i]} end def sort @cards.sort!{|x, y| x <=> y} end def to_s @cards.collect{|c| "#{COLOR[c.color]} #{POINT[c.point]}"}.join("\n") end end class Card attr_accessor :color, :point def initialize(color, point) @color, @point = color, point end def <=>(obj) color == obj.color ? obj.point <=> point : color <=> obj.color end end deck = Deck.new deck.shuffle puts "\n----shuffle-----\n#{deck}" deck.sort puts "\n----sort-----\n#{deck}"
Views: 684   Replies: 0   Tags: ruby
 




login or sign up to participate.
Money_dollar moneywill