symbolic link
ln -s /home/user/railsapps/app1/public /home/user/public_html/app1
567 users tagging and storing useful source code snippets
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!)
ln -s /home/user/railsapps/app1/public /home/user/public_html/app1
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
controller.controller_name
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| %>> <%= entry.body %> <% end %> 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
@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(', ') + '
' end @out = x @connection.logout
%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
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
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
class HelpController < ApplicationController def index end def tutorial end def faq end end
class ApplicationController < ActionController::Base def self.simple_action(*actions) actions.each {|action| class_eval("def #{action}; end")} end end
class HelpController < ApplicationController simple_action :index, :tutorial, :faq end
perl -pi -e 's|^#!/.*|#!/usr/bin/env ruby|;' script/* script/*/* public/dispatch.*
script/plugin install \ http://svn.globalize-rails.org/svn/globalize/globalize/trunk rake globalize:setup
include Globalize Locale.set_base_language 'en-US'
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
class Blog < ActiveRecord::Base translates :title, :post end
<%= render :partial => "thing", :collection => @coll, :spacer_template => "filename_to_file_with_hr_inside_it" %>
<%= @coll.map { |item| render :partial => "thing", :locals => {:thing => item} }.join("
") %>
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
#!/usr/bin/ruby list = IO.popen("svn st") list.each {|i| if (i =~ /^\?\s*(.*)/) cmd = "svn add '"+$1+"'" print cmd + "\n" system(cmd) end }
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
cd [RAILS_ROOT] svn ps svn:externals "rails http://dev.rubyonrails.org/svn/rails/tags/rel_1-0-0/" vendor svn up
cd [RAILS_ROOT] rake freeze_edge REVISION=3303
#!/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
create_table :table_name, :id => false do |t| end