« Newer Snippets
Older Snippets »
14 total  XML / RSS feed 

Upload Image To Database

// Code To Upload an image to a database and then update its contents.

# Create an ew classified and attach an image with it.
def create
  image_types = ["image/jpeg", "image/pjpeg", "image/gif","image/png", "image/x-png"]
  @categories = Category.find(:all)
  @classified = Classified.new(params[:classified])
  @classified.user = session[:user]
  unless params[:classified][:picture].blank?
    if (image_types.include?params[:classified][:picture].content_type.chomp)
      @classified.picture = params[:classified][:picture].read
    else
      @classified.errors.add(:picture,  "Photo doesn't seem to be JPG, GIF, or PNG. please ensure it is a valid image file.")
      render :action => 'new'
      return
    end
  end

  if @classified.save
    redirect_to :action => 'list'
  else 
    render :action => 'new'
  end
end


# Update Method So user can change the image associated with their classified
def update
  image_types = ["image/jpeg", "image/pjpeg", "image/gif", "image/png", "image/x-png"]
  @classified = Classified.find(params[:id])
  @categories = Category.find(:all)
  
  if @classified.update_attributes(params[:classified])
    unless params[:classified][:picture].blank?
      if (image_types.include?params[:classified][:picture].content_type.chomp)
        @classified.picture = params[:classified][:picture].read
      else
        @classified.errors.add(:picture, " doesn't seem to be JPG, GIF, or PNG. please ensure it is a valid image file.")
        render :action => 'edit'
        return
      end
    end
    
    flash[:notice] = 'Classified was successfully updated.'
    redirect_to :action => 'show', :id => @classified
  else
    render :action => 'edit'
  end
end

Extend FileColumn to work with ActsAsPartitionnedID


# environment.rb
module FileColumn
  class PermanentUploadedFile    
    alias_method :orig_move_from, :move_from
    def move_from(local_dir, just_uploaded)
      FileUtils.rm_rf @dir
      
      part_it_options = @instance.class.acts_as_partitioned_id_options
      partition_length = part_it_options[:digits] / part_it_options[:partitions]
      #last_partition = @dir[-partition_length.to_i..-1]
      the_rest = @dir[0...-partition_length.to_i]
      FileUtils.mkpath the_rest
      
      FileUtils.mv local_dir, @dir
      @just_uploaded = just_uploaded
    end
    
    private
    alias_method :orig_relative_path_prefix, :relative_path_prefix
    def relative_path_prefix
      raise RuntimeError.new("Trying to access file_column, but primary key got lost.") if @instance.partitioned_id.to_s.empty?
      @instance.partitioned_id.to_s
    end
  end
end

Extend FileColumn to work with ActsAsPartitionnedID


# environment.rb
module FileColumn
  class PermanentUploadedFile    
    alias_method :orig_move_from, :move_from
    def move_from(local_dir, just_uploaded)
      FileUtils.rm_rf @dir
      
      part_it_options = @instance.class.acts_as_partitioned_id_options
      partition_length = part_it_options[:digits] / part_it_options[:partitions]
      #last_partition = @dir[-partition_length.to_i..-1]
      the_rest = @dir[0...-partition_length.to_i]
      FileUtils.mkpath the_rest
      
      FileUtils.mv local_dir, @dir
      @just_uploaded = just_uploaded
    end
    
    private
    alias_method :orig_relative_path_prefix, :relative_path_prefix
    def relative_path_prefix
      raise RuntimeError.new("Trying to access file_column, but primary key got lost.") if @instance.partitioned_id.to_s.empty?
      @instance.partitioned_id.to_s
    end
  end
end

Extend FileColumn to work with ActsAsPartitionnedID


# environment.rb
module FileColumn
  class PermanentUploadedFile    
    alias_method :orig_move_from, :move_from
    def move_from(local_dir, just_uploaded)
      FileUtils.rm_rf @dir
      
      part_it_options = @instance.class.acts_as_partitioned_id_options
      partition_length = part_it_options[:digits] / part_it_options[:partitions]
      #last_partition = @dir[-partition_length.to_i..-1]
      the_rest = @dir[0...-partition_length.to_i]
      FileUtils.mkpath the_rest
      
      FileUtils.mv local_dir, @dir
      @just_uploaded = just_uploaded
    end
    
    private
    alias_method :orig_relative_path_prefix, :relative_path_prefix
    def relative_path_prefix
      raise RuntimeError.new("Trying to access file_column, but primary key got lost.") if @instance.partitioned_id.to_s.empty?
      @instance.partitioned_id.to_s
    end
  end
end

Rails Subversion First Checkout

// I use this for checking out a new rails project

svn checkout http://studicious.com/svn/trunk %1
svn remove log/*
svn commit -m "Removed log files"
svn propset svn:ignore "*.log" log/
svn update log/
svn commit -m "Ignoring log files"
svn remove tmp/*
svn propset svn:ignore "*" tmp/
svn update tmp/
svn commit -m "Ignoring temp folder"

Custom Validation in ActiveRecord

// allows adding errors in methods other than validate

  def other_errors=(err)
    write_attribute(:other_errors,Array.new) if !self.other_errors
    self.other_errors[self.other_errors.length] = err
  end
        
  def other_errors
    read_attribute(:other_errors)
  end

  def validate
    if self.other_errors
      self.other_errors.each {|x| errors.add_to_base(x)}
      return
    end
    return if !errors.empty?
  end

create a rails app from rails trunk, optionally committing to a subversion repository

I name this script railstrunk on my machine. So, usage would be:

railstrunk app_name


That creates a rails application under app_name.

If app_name is a subversion working copy, rails is set as an external and generated files are committed, and some ignore properties are set.

Here's how I'd go about creating a versioned rails app:

mkdir -p happy_app happy_app/trunk happy_app/tags happy_app/branches 
svn import happy_app http://myserver/myrepos/happy_app -m "Layout for happy_app"
rm -rf happy_app
svn co http://myserver/myrepos/happy_app/trunk happy_app
railstrunk happy_app


$rails_dir is set at the beginning of script, and it should be a path to a working copy of rails trunk on your machine. It's merely used to speed things up, it's not necessary.

Notice I remove the silly public/index.html from the generated app.

And now the code:

#!/bin/bash

rails_dir=~/code/ruby/rails

if [ $# != 1 ]; then
  echo "Usage: $0 app_name"
  echo
  echo "Creates a rails application under app_name."
  echo
  echo "If app_name is a subversion working copy, rails is set as an external"
  echo "and generated files are committed."
  echo
  echo "If $rails_dir exists, things are sped up by either symlinking it"
  echo "(for non-versioned apps) or copying it to the vendor dir."
  echo
  echo "$rails_dir should be a rails trunk working copy."
  exit
fi

dir=$1
mkdir -p $dir
cd $dir

if [ -n "`ls`" ]; then
  echo "Can't create app: $dir is not empty." >&2
  exit 1
fi

if [ -d $rails_dir ]; then
  if [ "`svn info $rails_dir 2>/dev/null | grep URL:`" != "URL: http://dev.rubyonrails.org/svn/rails/trunk" ]; then
    echo "$rails_dir is not a rails trunk working copy. Not going to use it." >&2
  elif [ -n "`svn st $rails_dir`" ]; then
    echo "$rails_dir is modified. Not going to use it." >&2
  else
    use_rails_dir=1
  fi
fi

if [ -z "`svn info 2>/dev/null`" ]; then
  mkdir vendor
  if [ -n "$use_rails_dir" ]; then
    ln -s $rails_dir vendor/rails
    cd vendor/rails
    svn up
    cd ../..
  else
    svn co http://dev.rubyonrails.org/svn/rails/trunk vendor/rails
  fi
  ruby vendor/rails/railties/bin/rails .
  rm public/index.html
else
  svn mkdir vendor
  svn ps svn:externals 'rails http://dev.rubyonrails.org/svn/rails/trunk' vendor
  svn ci -m 'set rails external to rails trunk'
  [ -n "$use_rails_dir" ] && cp -r $rails_dir vendor/rails
  svn up
  ruby vendor/rails/railties/bin/rails .
  rm public/index.html
  rm log/*
  mv config/database.yml config/database.yml.sample
  svn add . --force
  svn ps svn:ignore '*' tmp/cache tmp/pids tmp/sessions tmp/sockets
  svn ps svn:ignore 'database.yml' config
  svn ps svn:ignore '*.log' log
  svn ci -m "- created rails app
- moved database.yml to database.yml.sample
- deleted public/index.html
- ignored logs and tmp"
  cp config/database.yml.sample config/database.yml
fi

ActiveRecord attribute calls interception

I need to intercept attribute calls and add some additional info to them.

class ActiveRecord::Base
  def self.multilingual_field(fieldname)
    module_eval <<-end_eval
      def #{fieldname}
        send("#{fieldname}_\#{Locale.language.short_name}")
      end

      def #{fieldname}=(value)
        send("#{fieldname}_\#{Locale.language.short_name}=",value)
      end
    end_eval
  end
end

Default content-type in Rails

I always forget this.

class ApplicationController < ActionController::Base
  include AuthenticatedSystem
  
  before_filter :set_encoding
  
  private
    def set_encoding
      @headers["Content-type"] ||= "text/html; charset=utf8"
    end
end

Typo dispatch.fcgi

#!/usr/local/bin/ruby
#
# You may specify the path to the FastCGI crash log (a log of unhandled
# exceptions which forced the FastCGI instance to exit, great for debugging)
# and the number of requests to process before running garbage collection.
#
# By default, the FastCGI crash log is RAILS_ROOT/log/fastcgi.crash.log
# and the GC period is nil (turned off).  A reasonable number of requests
# could range from 10-100 depending on the memory footprint of your app.
#
# Example:
#   # Default log path, normal GC behavior.
#   RailsFCGIHandler.process!
#
#   # Default log path, 50 requests between GC.
#   RailsFCGIHandler.process! nil, 50
#
#   # Custom log path, normal GC behavior.
#   RailsFCGIHandler.process! '/var/log/myapp_fcgi_crash.log'
#
require File.dirname(__FILE__) + "/../config/environment"
require 'fcgi_handler'

RailsFCGIHandler.process!

link_to_remote not calling "complete"

<ul>
<% @items.each do |item| %>
>
<%= link_to_remote(item.name, 
{       
:url => { 
:controller => 'security', 
:action => 'add_security', 
:description => item.name, 
:symbol => item.symbol
},
:update     => {:success=>'indexFundList', :failure=>'notice'},
:position   => :bottom,
:loading    => "loading()",
:complete   => "completeAddIndexFund(request)"
})           -%>
>
<% end %>
>

Import of old Instiki data to a new Instiki instance

Trying to import data from Instiki.app 10.2 to Instiki 11.0 (alpha). The follow error is occurring.

 % ./instiki/script/import_storage -t instiki-old/2500 -i instiki-old/rb_src -d mysql -o instiki-data.sql
/users/home/quidire/web/public/instiki-old/rb_src/app/models/chunks/engines.rb:3:in `require': No such file to load -- redcloth (LoadError)
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/chunks/engines.rb:3
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/wiki_content.rb:2:in `require'
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/wiki_content.rb:2
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/revision.rb:2:in `require'
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/revision.rb:2
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/page.rb:3:in `require'
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/page.rb:3
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/web.rb:2:in `require'
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/web.rb:2
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/wiki_service.rb:7:in `require'
        from /users/home/quidire/web/public/instiki-old/rb_src/app/models/wiki_service.rb:7
        from ./instiki/script/import_storage:96:in `require'
        from ./instiki/script/import_storage:96

Select a State in Rails

<%= select(:shipaddress, :state, [   
        ['Select a State', 'None'],
        ['Alabama', 'AL'], 
        ['Alaska', 'AK'],
        ['Arizona', 'AZ'],
        ['Arkansas', 'AR'], 
        ['California', 'CA'], 
        ['Colorado', 'CO'], 
        ['Connecticut', 'CT'], 
        ['Delaware', 'DE'], 
        ['District Of Columbia', 'DC'], 
        ['Florida', 'FL'],
        ['Georgia', 'GA'],
        ['Hawaii', 'HI'], 
        ['Idaho', 'ID'], 
        ['Illinois', 'IL'], 
        ['Indiana', 'IN'], 
        ['Iowa', 'IA'], 
        ['Kansas', 'KS'], 
        ['Kentucky', 'KY'], 
        ['Louisiana', 'LA'], 
        ['Maine', 'ME'], 
        ['Maryland', 'MD'], 
        ['Massachusetts', 'MA'], 
        ['Michigan', 'MI'], 
        ['Minnesota', 'MN'],
        ['Mississippi', 'MS'], 
        ['Missouri', 'MO'], 
        ['Montana', 'MT'], 
        ['Nebraska', 'NE'], 
        ['Nevada', 'NV'], 
        ['New Hampshire', 'NH'], 
        ['New Jersey', 'NJ'], 
        ['New Mexico', 'NM'], 
        ['New York', 'NY'], 
        ['North Carolina', 'NC'], 
        ['North Dakota', 'ND'], 
        ['Ohio', 'OH'], 
        ['Oklahoma', 'OK'], 
        ['Oregon', 'OR'], 
        ['Pennsylvania', 'PA'], 
        ['Rhode Island', 'RI'], 
        ['South Carolina', 'SC'], 
        ['South Dakota', 'SD'], 
        ['Tennessee', 'TN'], 
        ['Texas', 'TX'], 
        ['Utah', 'UT'], 
        ['Vermont', 'VT'], 
        ['Virginia', 'VA'], 
        ['Washington', 'WA'], 
        ['West Virginia', 'WV'], 
        ['Wisconsin', 'WI'], 
        ['Wyoming', 'WY']]) %>

start my lighttpd-based rails app

/usr/local/sbin/lighttpd -f /home/avshop/lighttpd/lighttpd.conf
« Newer Snippets
Older Snippets »
14 total  XML / RSS feed