Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

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

symbolic link

ln -s /home/user/railsapps/app1/public /home/user/public_html/app1

Dynamic time based finder for ActiveRecord

I think it's pretty nice. Get all records within a railsified period of time (7.days.ago, 12.months.ago). I can do cool things like Workout.within_12_days or Workout.within_12_hours. Further conditions can be given as a hash, and will be transposed onto the end of the :conditions.

Workout.within_n_units(:user_id => 12) #-> Workout.find(:all, :conditions => 'created_at > n.units.ago and user_id = 12')


class Workout < ActiveRecord::Base
  class << self
    def within_n_temporal_units(number, units, further_conds={})
      conds = "created_at > '#{eval("#{number}.#{units}.ago").to_s(:db)}'"
      further_conds.each {|key, val| conds << " and #{key} = #{val}"}
      Workout.find(:all, :conditions => conds)
    end
    
    def method_missing(name, *args)
      return within_n_temporal_units($~[1], $~[2], args[0] || {}) if name.to_s =~ /within_(\d+)_(\w+)/
      raise NoMethodError, "undefined method `#{name}' for #{self}:Class"
    end
  end
end

Get the name of the controller used, when inside a view.

controller.controller_name

ActiveRecord DOM IDs

The solution—or at least a nice, cheap bandaid that can be applied easily, consists of adding a method to ActiveRecord::Base to help generate these ids without any brainpower involved.

Here’s a very simple implementation that I use in my projects, courtesy of Jamis Buck:



class ActiveRecord::Base
  def dom_id(prefix=nil)
    display_id = new_record? ? "new" : id
    prefix ||= self.class.name.underscore
    prefix != :bare ? "#{prefix.to_s.dasherize}-#{display_id}" : display_id
  end
endSo, you can do stuff like this in your views:

<ul>
<% @entries.each do |entry| %>
  <li id='<%= entry.dom_id %>'>
    <%= entry.body %>
  </li>
<% end %>
</ul>And stuff like this in your controller:

def remove_entry
  entry = JournalEntry.find(params[:id])
  update_page do |page|
    page[entry.dom_id].remove
  end
end

ruby stored procedures

There are alot of reasons to use stored procedures. One of the most compelling reasons is that a system has already been built with stored procedures and interfacing with it cannot be by raw SQL. This situation is mainly caused by DBA’s whose job it is to control the flow of information into and out of the database. In “enterprise” situations this is the norm.


  @connection = OCI8.new("fxblotter6", "fxblotter6", "fx10g")

  plsql = @conn.parse("BEGIN P_CURRENCY.select_currency(:out); END;")
  plsql.bind_param(':out', OCI8::Cursor) 
  plsql.exec

  cursor = plsql[':out']
  plsql.close

  x = ''
  while r = cursor.fetch()
    x = x + r.join(', ') + '<br>'
  end

  @out = x

  @connection.logout


http://blog.hksintl.com/

Фильтр на обновление только разрешенных полей

%w(name email address).each { |f| @person[f] = params[:person][f] }

Перегрузка ошибок

Перегрузка ошибок

def error_messages_for(object_name, options = {})
        options = options.symbolize_keys
        object = instance_variable_get("@#{object_name}")
        if object && !object.errors.empty?
          content_tag("div",
            content_tag(
              options[:header_tag] || "h2",
              "Из-за #{object.errors.count} #{object.errors.count.items("ошибки", "ошибок", "ошибок")}  #{object_name.ru_name} не будет сохранена"
            ) +
            content_tag("p", "Следующие поля заполнены неверно:") +
            content_tag("ul", object.errors.full_messages.collect { |msg| content_tag("li", msg) }),
            "id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation"
          )
        else
          ""
        end
       end

Компоненты в rails

У рельсов плохо с компонентами,
потому что DHH не одобряет. В качестве
опции:


module Sidebar 
        def self.append_features(controller) 
                controller.send(:before_filter, :generate_sidebar) 
                controller.send(:helper_method, :sidebar) 
                super(controller) 
        end 

        def generate_sidebar 
                @sidebar_items = # bla bla bla 
        end 

        def sidebar 
                render_to_string # bla bla bla 
        end 
end 

class SomeController < ApplciationController 
        include Sidebar 
end 


и в темплейтах где нада <%= sidebar %>

естественно в таком случае следует
аккуратно избегать рекурсии ;-)

Modify acts_as_urlnameable to un-accentuate unicode chars

The acts as urlnameable plugin (used to create permalinks) removes accentuated chars by default.

Change the urlnameify method in lib/acts_as_urlnameable.rb:74

def urlnameify(text)
  t = Iconv.new('ASCII//TRANSLIT', 'utf-8').iconv(text)
  t = t.downcase.strip.gsub(/[^-_\s[:alnum:]]/, '').squeeze(' ').tr(' ', '-')
  (t.blank?) ? '-' : t
end

DRY up empty controller actions

Ever create Rails views that don't user the controller at all just to take advantage of an application layout?
If you have, you may have a lot of code that looks like this:


class HelpController < ApplicationController
  def index
  end

  def tutorial
  end

  def faq
  end
end


Well, there's a simple way to make this a lot cleaner...


class ApplicationController < ActionController::Base
  def self.simple_action(*actions)
    actions.each {|action| class_eval("def #{action}; end")}
  end
end

Now your controller can look like this instead...

class HelpController < ApplicationController
  simple_action :index, :tutorial, :faq
end

Replacing all shebangs in a rails app

perl -pi -e 's|^#!/.*|#!/usr/bin/env ruby|;' script/* script/*/* public/dispatch.*

Setup Globalize plugin in Rails

Don't forget to edit config/database.yml first.

Terminal:
script/plugin install \
    http://svn.globalize-rails.org/svn/globalize/globalize/trunk 
rake globalize:setup 


…in config/environment.rb:
include Globalize
Locale.set_base_language 'en-US'


…in the app controller, before any other filter:
  before_filter :set_locale
  # FIXME, NOT TESTED YET, PROBABLY DOESN'T WORK.
  def set_locale
    if params[:locale]
      # The user has explicitly requested a locale.
      session[:locale] = params[:locale]
      Locale.set params[:locale]
    elsif session[:locale].empty?
      # The user has a current session.
      Locale.set session[:locale]
    elsif ! request.env["HTTP_ACCEPT_LANGUAGE"].empty?
      # We use the browser's locale settings.
      Locale.set request.env["HTTP_ACCEPT_LANGUAGE"][/[a-z]{2}-[a-z]{2}/i]
    else
      # the default locale defined in config/environment.rb is used.
    end
  end


…in the model:
class Blog < ActiveRecord::Base
  translates :title, :post
end

Substitute for the :spacer_template option to rail's "render" method

when working with the :collection option, it seems silly to have to have an entire file just for a spacer, which would probably just be something like "<hr />" for most, so this is a great substitute for
<%= render :partial => "thing", :collection => @coll, :spacer_template => "filename_to_file_with_hr_inside_it" %>


New version with code embedded:
  <%= @coll.map { |item| render :partial => "thing", :locals => {:thing => item} }.join("<hr />") %>

Copy data from database into fixtures

Take from pylonhead.com

  def self.to_fixture
    write_file(File.expand_path("test/fixtures/#{table_name}.yml", RAILS_ROOT),
      self.find(:all).inject("---\n") { |s, record|
        self.columns.inject(s+"#{record.id}:\n") { |s, c|
          s+"  #{{c.name => record.attributes[c.name]}.to_yaml[5..-1]}\n" }
    })
  end

Add all new files to subversion (usefull with rails)

Just run this code from inside your repository. This will do an "svn add" on each file marked as "?" when doing "svn status"

Beware: this code might break with multi word filenames...

#!/usr/bin/ruby
list = IO.popen("svn st")
list.each {|i|
if (i =~ /^\?\s*(.*)/) 
    cmd = "svn add '"+$1+"'"
    print cmd + "\n"
    system(cmd)
end
}

Very simple act_as base file

This is a very simple file to show how to add 'act_as_whatever' to ActiveRecord.

To use it, put the code into a file like lib/your_super_name/acts/idiot.rb and voilà.
Thanks to technoweenie for "acts_as_paranoid" which I used with "acts_as_tree" to build this template.

module YourSuperName
  module Acts
    module Idiot
      # this is called when the module is included into the 'base' module
      def self.included(base)
        # add all methods from the module "AddActsAsMethod" to the 'base' module
        base.extend AddActsAsMethod
      end
      module AddActsAsMethod
        def acts_as_idiot
          # BELONGS_TO HAS_MANY GOES HERE

          class_eval <<-END
            include YourSuperName::Acts::Idiot::InstanceMethods
          END
        end
      end
      
      
      module InstanceMethods
        def self.included(aClass)
          aClass.extend ClassMethods
        end

        # PUT YOUR INSTANCE METHODS HERE
        def idiot(msg)
          "#{self}: I am an idiotic object. And I say '#{msg}'."
        end
        
        module ClassMethods
          # PUT YOUR CLASS METHODS HERE
          def idiot(msg)
          "#{self}: I am an idiotic class. And I say '#{msg}'."
          end
        end
      end
    end
  end
end

ActiveRecord::Base.send :include, YourSuperName::Acts::Idiot

Freezing rails into vendor

If you are using subversion:

cd [RAILS_ROOT]
svn ps svn:externals "rails http://dev.rubyonrails.org/svn/rails/tags/rel_1-0-0/" vendor
svn up


not using subversion:

cd [RAILS_ROOT]
rake freeze_edge REVISION=3303

Bash script to perform initial import of a rails project

This is still a work in progress. The objective is to script the entire initial svn hassle that needs to be done with a rails project. The first import, then the first checkout, and then dealing with all the files that need to be ignored. Based heavily on:

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

In the future I may add capistrano setup and such.

This worked the last time I tried it, but I don't expect it to work the next time.

#!/bin/bash
set -v                         # verbose output

## USAGE: configure the following variables, and execute in your rails root, ie the directory with
## config/ and app/
## NOTE: This script assumes that your directory of your rails root has the same name as both your 
## application, and your svn repo.
##
## This script also assumes that it's ok to make a backup in the parent directory of your
## rails root.

username="jonshea"               # CHANGE ME!!!!!!!
svn_url="http://jonshea.com/svn/" # CHANGE ME!!!!!

## This is still a work in progress. The objective is to script the entire initial svn hassle that 
## needs to be done with a rails project. The first import, then the first checkout, and then 
## dealing with all the files that need to be ignored. Based heavily on: 
##
## http://wiki.rubyonrails.org/rails/pages/HowtoUseRailsWithSubversion
##
## It designed only for freshly created applications, that haven't really be changed at all from the
## original generation script

app_dir=`pwd`
app_name=`basename $app_dir`
svn_url_to_your_repository=${svn_url}${app_name} # Assumes your repo has the same name as your app
echo $app_name
echo $svn_url_to_your_repository

## Do the initial import
svn import . ${svn_url_to_your_repository}/trunk -m "First Import" --username $username



cd ..                           # Back out a directory from the root

## We're going to make a backup of your app. If one is already there, then remove it.
test -d ./pre_svn_backup_$app_name || rm -rf pre_svn_backup_$app_name
mkdir ../pre_svn_backup_$app_name
mv -f $app_dir ./pre_svn_backup_${app_name} # Move the rails app to the backup dir.

mkdir $app_dir # recreate the application directory
cd $app_dir
svn checkout ${svn_url_to_your_repository}/trunk . # Check out the subversion repo to the app directory

## This section cleans up the svn repo, so that you're not versioning things that shouldn't be versioned.
svn remove log/*
svn commit -m 'removing all log files from subversion'
svn propset svn:ignore "*.log" log/
svn update log/
svn commit -m 'Ignoring all files in /log/ ending in .log'

svn remove tmp/
svn commit -m 'removing the temp directory from subversion'
svn propset svn:ignore "*" tmp/
svn update tmp/
svn commit -m 'Ignore the whole tmp/ directory, might not work on subdirectories?'

svn move config/database.yml config/database.example
svn commit -m 'Moving database.yml to database.example to provide a template for anyone who checks out the code'
svn propset svn:ignore "database.yml" config/
svn update config/
svn commit -m 'Ignoring database.yml'

svn move public/dispatch.rb public/dispatch.rb.example
cp public/dispatch.rb.example public/dispatch.rb
svn move public/dispatch.cgi public/dispatch.cgi.example
cp public/dispatch.cgi.example public/dispatch.cgi
svn move public/dispatch.fcgi public/dispatch.fcgi.example
cp public/dispatch.fcgi.example public/dispatch.fcgi
svn commit -m 'Moving dispatch.(star) to dispatch.(star).example to provide a template.'

svn propedit svn:ignore public/ dispatch.rb
svn propedit svn:ignore public/ dispatch.cgi
svn propedit svn:ignore public/ dispatch.fcgi
svn update public/
svn commit -m 'Ignoring dispatch.* files'

svn propedit svn:ignore db/ *.sqlite
svn propedit svn:ignore db/ *.sqlite3
svn commit -m 'Ignore database files'




#cap --apply-to $app_dir $app_name
#svn add config/deploy.rb     
#svn add lib/tasks/capistrano.rake

exit 0

lighttpd url rewrite

url.rewrite = ( "^/$" => "index.html", "^([^.]+)$" => "$1.html" )

Creating a table with migrations when using has_and_belongs_to_many

You can find the information at http://api.rubyonrails.org under the "create_table" method. The short answer is this though,

create_table :table_name, :id => false do |t|

end


:id is the part you're looking for, it defaults to true, which creates the :id as an autoincrementing primary key, if you use migrations and want to create the join table, you don't want an "id" column, so use :id => false to override the create_table method and tell it you don't want that primary key.
« Newer Snippets
Older Snippets »
50 total  XML / RSS feed