Tagrails

Do you need to change a filename before sending it ?

Rails action to send binary data

I have one old application where the attachment is store as an id in the filesystem. The customer wants to have the attachment with the right name. So I have made this small action which accepts the id of the requested object and send the file data.


  def send_bios
    redirect_to :action => 'bios' if params[:id].blank?
    @artist = Artist.find(params[:id]);
    contents = File.open(@artist.bios_path,"rb") {|io| io.read}
    send_data contents, :filename => "#{@artist.name}.pdf", :type => "application/pdf", :disposition => 'attachment'
  end

Random images helper for Rails

Here is how to make random images generation for your website.

First you must put your images in a folder /public/images/random_images or what ever.

Second you put images there and mark the filenames with a prefix, which image to which section will be visible on.

index_bottom_1.jpg -> for the index page on the bottom :)

index_bottom_2.jpg -> for the index page on the bottom

featured_art_1.jpg -> some panel.

featured_art_2.jpg -> some panel.

and so on…

Paste this method in your base controller. This method will be called to make list for a specific image folder and “filter” the images that are supposed to be showed in the different regions in @variables.

  before_filter :init_random_images
  protected # :) be carefull for this if you copy paste
  def init_random_images
    # collect some static images
    web_root = "images/imagestorage/random_images"

    all_images = Dir["#{RAILS_ROOT}/public/#{web_root}/*.jpg"]

    @random_head_images = []
    @random_indexbtm = []
    @random_featured = []
    @random_sales = []
    @random_services = []
    @random_framing = []
    @random_artistcollection = []
    all_images.each do |f|
      if File.stat(f).file?
        @random_head_images << ("/#{web_root}/" + File.basename(f)) if f =~ /head_images_/
        @random_indexbtm << ("/#{web_root}/" + File.basename(f)) if f =~ /indexbtm_/
        @random_featured << ("/#{web_root}/" + File.basename(f)) if f =~ /featured_/
        @random_sales << ("/#{web_root}/" + File.basename(f)) if f =~ /sales_/
        @random_services << ("/#{web_root}/" + File.basename(f)) if f =~ /services_/
        @random_framing << ("/#{web_root}/" + File.basename(f)) if f =~ /framing_/
        @random_artistcollection << ("/#{web_root}/" + File.basename(f)) if f =~ /artistcollection_/
      end
    end

Then paste this as a helper or in the base controller, to use it in your views. The method will give you from the images array, count number of images.

  helper_method :get_random_image
  def get_random_image(images, count)
    requested_images = []
    images_copy = images.clone
    [images_copy.size, count].min.times do
      index = rand(images_copy.size)
      requested_images << images_copy[index]
      images_copy.delete_at(index)
    end
    requested_images.flatten.compact
  end

here is an example how to use it.

<div id="static_logo" style="background:url(<%= get_random_image(@random_sales, 1) %>) no-repeat scroll left top;">
 

Future optimization

Put some caching, not to make

Dir["#{RAILS_ROOT}/public/#{web_root}/*.jpg"]
 

on every request.

10x Bl8cki to the nice code optimizations :)

Rails conf 2008/6/2

Its aways nice to know whats going on in rails field

http://railsenvy.com/2008/6/2/Railsconf-videos

Whats new for me was flog:

  • http://on-ruby.blogspot.com/2007/12/flog-profiling-complexity.html
  • http://ruby.sadi.st/Flog.html

Some more video links

Only get, head, post, put, and delete requests are allowed.

I got this error when I have to upgrade one old project from rails 1.2.5 to rails 2.1 (the problem is not in rails)

ActionController::MethodNotAllowed

Only get, head, post, put, and delete requests are allowed.

The exception:

ActionController::MethodNotAllowed (Only get, head, post, put, and delete requests are allowed.):
    /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/routing/recognition_optimisation.rb:65:in `recognize_path'
    /usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_controller/routing/route_set.rb:384:in `recognize'

I got this error only when I access URL’s with param like

http://127.0.0.1:3000/dod/images/show_big_image/1639

I found that the problem was in the :id because without the :id the method was called correctly

This means that there is something with the routes.

Not working routes.rb: ….

  map.connect '', :controller => 'auth'

  # Install the default route as the lowest priority.
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:sort_key/:sort_order'

it will work if you swap the last two lines….

  map.connect '', :controller => 'auth'

  # Install the default route as the lowest priority.
  map.connect ':controller/:action/:sort_key/:sort_order'
  map.connect ':controller/:action/:id'

It seems that it does reading the comments in the routes.rb is usefull. There is written:

# Install the default route as the lowest priority.

This error also occurs if you haven't restart your webserver. I know that there is no need to restart it but its true, try restarting and check.

Rails plugins, gems, search engines, applications

Plugins & gems lists

Associations

http://www.workingwithrails.com/railsplugin/4801-has-many-polymorphs

Versioning of AR

http://github.com/fatjam/acts_as_revisable/tree/master

http://opensoul.org/2006/7/21/acts_as_audited

Scafolding

http://streamlinedframework.org/pages/about

Ajax pagination with JQuery

http://ozmm.org/posts/ajax_will_paginate_jq_style.html

Find_by_param is a nice and easy way to handle permalinks and dealing with searching for to_param values

http://github.com/bumi/find_by_param/tree/master

Asset Plugin – better than rails 2.0 integrated

Asset Packager

Image Magic

http://vantulder.net/rails/magick/

OpenID

http://wiki.rubyonrails.org/rails/pages/OpenidLoginGenerator

http://github.com/technoweenie/restful-authentication/tree/master

http://github.com/mrflip/

Model graph visualize

Article on franzens.org

  • http://visualizemodels.rubyforge.org/
  • http://rav.rubyforge.org/
  • http://railroad.rubyforge.org/

Simple Captcha

http://expressica.com/simple_captcha/

Memcached stuff

http://townx.org/rails_and_memcached

Good rails 2.1 overview

memcached -vv -l 127.0.0.1 -p 11211 -m 256 -P /tmp/memcached.pid -u mongrel

memcached-tool 127.0.0.1

monitor the connections with the hidden option in the memcached-tool

echo $(($(netstat -nt | grep 11211 | grep -v WAIT | wc -l)/2)); ./memcached-tool 127.0.0.1:11211 dump > memdump; cat memdump

memcached-tool

alternative memcached client

PDF Output

http://ruby-pdf.rubyforge.org/pdf-writer/

http://rubyforge.org/projects/railspdfplugin/

Somone example report

Need to be checked: http://code.rubyreports.org/

Reporting

ruport & acts_as_reportable
some java reporting into rails

Sending Email

Inline email attachments plugin: http://flow.handle.it/past/2007/11/5/inline_attachment_now_official_rocks/

Wiki integration

http://github.com/queso/signal-wiki/tree/master

Repositories

http://github.com/mrflip/

Tutorials

Rails2.0 Video http://www.vimeo.com/425800

http://media.rubyonrails.org/video/rails_take2_with_sound.mov

http://akitaonrails.com/2007/12/12/rolling-with-rails-2-0-the-first-full-tutorial

http://akitaonrails.com/2007/12/12/rolling-with-rails-2-0-the-first-full-tutorial-part-2

Performance and Loging

Announcing Clientperf: Simple Client-Side Rails Performance

web statistics

http://www.railstat.com/wiki/FAQ

http://haveamint.com/about/feature_highlights – not free

production log analyzers

webstat like: http://watson.rubyforge.org/

speed: http://github.com/wvanbergen/request-log-analyzer/wikis

speed: http://ckhsponge.wordpress.com/2006/10/11/ruby-on-rails-log-analyzer-rawk/

pl-analyse: http://seattlerb.rubyforge.org/production_log_analyzer http://seattlerb.rubyforge.org/production_log_analyzer

Open source rails projects

Server setup

capistrano

mod_rails

  • http://www.sysadminschronicles.com/articles/2008/05/13/ubuntu-8-04-rails-server-using-passenger-part-2

nginx

  • check my post
  • gem install nginx_config_generator

will_paginate with ajax

It is very easy to handle ajax pagination as described on this post here.

I want to give one full example.

Here is how my form looks:

<% form_remote_tag :url => {
                      :action => 'handle_urls',
                      :script_id => @script,
                      :page => params[:page],
                    },
  :html => {:id => 'f'},
  :update => "filtered_articles_pane" do %>

Here is how my will_paginate helper looks:

<%= will_paginate @filtered_urls,
  :renderer => 'RemoteLinkRenderer',
  :remote => { :with => "'script_id=#{@script.id}&approved_flag='+$(\'approved_flag\')",
  :update => 'filtered_articles_pane'} %>

I have used the improved version of the will_paginate:

# Use it like so…
# will_paginate :collection, :remote => {:with => 'value', :update => 'some_div'} 

class RemoteLinkRenderer < WillPaginate::LinkRenderer
  def initialize(collection, options, template)
    @remote = options.delete(:remote)
    super
  end

  def page_link_or_span(page, span_class = 'current', text = nil)
    text ||= page.to_s
    if page and page != current_page
      @template.link_to_remote(text, {:url => url_options(page), :method => :get}.merge(@remote))
    else
      @template.content_tag :span, text, :class => span_class
    end
  end
end

Update for will_paginate 2.3.x

# app/helpers/remote_link_renderer.rb

class RemoteLinkRenderer < WillPaginate::LinkRenderer
  def prepare(collection, options, template)
    @remote = options.delete(:remote) || {}
    super
  end

protected
  def page_link(page, text, attributes = {})
    @template.link_to_remote(text, {:url => url_for(page), :method => :get}.merge(@remote))
  end
end

Rails 2.0 scaffolding

The most valuable usage for scaffolding is when you use it in the administration part of the site. The administration is usually separated in separate module/folder.

The new rails scaffolding is not good because:

  • It is time taking to setup nested scaffold
  • I have tons of uselss source code in the scaffolding like respond_to ... that is usable very rare or never.
  • The HTML that is generated is ugly and not usable for CSS skin
  • Not using the nice ruby style iterations .each instead of for's
  • Code repetition, the “new” and the “edit” views has the same form elements
  • Not easy to find documentation

I find Akita article for scaffolding. It is is great that he has covered some real cases. It is a lot of reading and I must read/copy/paste every time I need to make a scaffold. Here is step by step on making scaffold for administration.

  • ruby script/generate scaffold admin::BadArticle NOT PLURAL!
    • user:references
    • description:text,string
    • fixed:boolean
    • timestamps are automaticaly added
  • Add in routes.rb
    • map.namespace :admin do |admin|
        admin.resources :bad_articles
      end
  • Model
    • Rename admin::BadArticles -> BadArticle,
    • move it to the model directory
    • rename the file
  • Fix the migration file:
    • remove the prefix from the migration class,
    • remove the prefix from table name
    • rename the file
  • URL references
    • admin_bad_articles_url
    • redirect_to([:admin, bad_article])
  • Controller
    • rename all Admin::BadArticles -> BadArticle except in the controller name
    • Probably you will want to make your scaffold inhired your base admin controller
    • def create
         ...
         format.html { redirect_to([:admin, @filtered_url]) }
         ...
      end
    • def update
          ...
              format.html { redirect_to([:admin, @filtered_url]) }
          ...
      end
    • class Admin::BadArticlesController < ApplicationController
      class Admin::BadArticlesController < Admin::AuthController
        layout 'admin'
       (in case that you don't have it in the base controller)
    • def index
        @admin_bad_articles = BadArticle.find(:all)
        respond_to do |format|
          format.html # index.html.erb
          format.xml  { render :xml => @admin_bad_articles }
        end
      end
  • Index.rhtml.erb
    • <td><%= link_to 'Edit', edit_admin_bad_article_path(bad_articles) %></td>
    • <%= link_to 'New bad_articles', new_admin_bad_articles_path %>
  • edit.rhtm
    • <%= link_to 'Show', @bad_article %> |
      <%= link_to 'Back',bad_articles_path %><%= link_to 'Show', [:admin, @bad_article_url] %> |
      <%= link_to 'Back', admin_bad_articles_path %>
  • show.html.erb
    • <%= link_to 'Edit', edit_filtered_url_path(@filtered_url) %> |
      <%= link_to 'Back', filtered_urls_path %>
  • new.rhtml
    • <% form_for(@bad_article) do |f| %><% form_for([:admin, @bad_article]) do |f| %>
    • <%= link_to 'Back', bad_articles_path %><%= link_to 'Back', admin_bad_articles_path %>

Traps:

The order of the routes in routes.rb does matter! In order to make the REST work you must have this block at the bottom of your routes.rb like this:

map.namespace :admin do |admin|
  admin.resources :bad_articles
end
# Install the default route as the lowest priority.
map.connect ':controller/:action/:id.:format'
map.connect ':controller/:action/:id'


Remove simply_helpful plugin if you get the error:

undefined method `new_record?' for #Array:0x532a3e8

Debuging tools:

rake routes

Tips:

How to add custom actions to the REST

map.namespace :admin do |admin|
  admin..esources :bad_articles, :member => {:toggle => :get}
  admin.resources :orders, :member => { :resend => :post }
  admin.resources :users,  :collection => { :filter => :any }
end

Then in the controller:

def toggle
  @bad_article = BadArticle.find(params[:id])
  @bad_article.fixed = ! @bad_article.fixed
  @bad_article.save
  redirect_to  admin_bad_articles_url
end

And in the view:

<%= toggle_admin_bad_article_url(filtered_url) %>

More reading here

Resources:

Rails code-snipplets

auto_scope

source: http://blog.teksol.info/archives/2007/3

class Contact < ActiveRecord::Base
auto_scope \
:old => {:find => {:conditions => [born_on < ?, 30.years.ago]}},
:young => {:find => {:conditions => [born_on > ?, 1.year.ago]}}
end

class Testimonial < ActiveRecord::Base
auto_scope \
:approved => {
:find => {:conditions => [approved_at < ?, proc {Time.now}]},
:create => {:approved_at => proc {Time.now}}},
:unapproved => {
:find => {:conditions => approved_at IS NULL},
:create => {:approved_at => nil}}
end

Rails internals!?

http://localhost:3000/rails/info/properties

Threads

© 2024 Gudasoft

Theme by Anders NorénUp ↑