DZone 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

Snippets

  • submit to reddit

Recent Snippets

                    Found via the RoR wiki. Solution courtesy of Jakob S.

Assuming a schema like such:

create table node (
  id integer primary key,
  name varchar(32)
);

create table nodelink (
  source_id integer,
  destination_id integer
);

A Rails association like this would supposedly do the job:

has_and_belongs_to_many :nodes, :join_table => 'nodelink', :association_foreign_key => 'destination_id', :foreign_key => 'source_id'
                
                    You can simulate the MySQL group_concat aggregate function using the SQLite/Ruby create_aggregate method (documented here
http://docs.jamisbuck.org/read/chapter/17#page77 ), as follows:

require 'sqlite3'

db = SQLite3::Database.open("test.db")

db.create_aggregate("group_concat", 1) do
  step do |func, value|
    if String(func[:concat]).empty? then
      func[:concat] = String(value)
    else
      func[:concat] = String(func[:concat]) + " " + String(value)
    end
  end

  finalize do |func|
    func.result = func[:concat]
  end
end

db.execute "select grouper, group_concat(name) from tests group by grouper" do |row|
  p row
end

db.close

Test with a SQLite3 database containing the following:

CREATE TABLE tests (id integer primary key, name test, grouper text);
INSERT INTO "tests" VALUES(1, 'Foo', '1');
INSERT INTO "tests" VALUES(2, 'Bar', '1');
INSERT INTO "tests" VALUES(3, 'ABC', '2');
INSERT INTO "tests" VALUES(4, 'DEF', '2');
INSERT INTO "tests" VALUES(5, 'GHI', '2');
INSERT INTO "tests" VALUES(6, 123, '3');

Gives these results:

["1", "Foo Bar"]
["2", "ABC DEF GHI"]
["3", "123"]
                
                    Found this on the #rubyonrails irc log here http://www.loglibrary.com/show_page/view/62?Multiplier=60&Interval=18&StartTime=1115561823 - credit goes to <tufty>.

Problem: you want to get at the underlying database connection object, e.g. so you can do something like create_function or create_aggregate on a SQLite database.  You try ActiveRecord::Base.connection but that just gives you the Rails connection adapter, not the underlying database connection.

Solution:

db = ActiveRecord::Base.connection.instance_variable_get(:@connection)
db.create_aggregate("xxx", 1) do
etc.
                
                    
class Array
    def swap!(a,b)
         self[a], self[b] = self[b], self[a]
    self
    end
end

You can now do stuff like..

[1,2,3,4].swap!(2,3)  # = [1,2,4,3] etc..

Many thanks to Sam Stephenson and technoweenie for their suggestions.                
                    Code by Laurens van der Oever -- http://laurens.vd.oever.nl/weblog/items2005/setsinjavascript/

function set () {
    var result = {};

    for (var i = 0; i < arguments.length; i++)
      result[arguments[i]] = true;

    return result;
}

Check something like so:

var typeInSet = nodeType in set(2, 3, 4, 7, 8);
                
                    Here's a controller code snippet for doing partial validations on Rails model objects:
  private
    def get_partial_user_from_session
      unless @session['partial_user'].nil?
        @user = @session['partial_user']
      else
        @user = User.new
      end
    end

    def save_partial_user_in_session
      unless @user.nil?
        @session['partial_user'] = @user
      end
    end
    
    # Might be a good addition to AR::Base
    def valid_for_attributes( model, attributes )
      unless model.valid?
        errors = model.errors
        our_errors = Array.new
        errors.each { |attr,error|
          if attributes.include? attr
            our_errors << [attr,error]
          end
        }
        errors.clear
        our_errors.each { |attr,error| errors.add(attr,error) }
        return false unless errors.empty?
      end
      return true
    end

To ensure the errors are cleared out properly on each request add a before_filter with the following:
    def clear_stage_errors
      unless @session['partial_user'].nil?
        @session['partial_user'].errors.clear
      end
    end

You can use 
get_partial_user_from_session
 and 
save_partial_user_in_session
 as before and after filters, respectively, so you only have to reference @user in your multi-step controller.

A clean way to arrange the view is to have each step in its own partial, and set a variable such as 
@current_stage
 in your controller, then in your view just do something like:
<%= start_form_tag({:action=> "signup"} , { :name => 'signupform' }) %>
<%= hidden_field_tag "changeCountry" %>
<%= hidden_field_tag "current_stage", "#{@current_stage}"%>

<h2>Registration Process</h2>
<%= @flash['notice'] %>

<%= render_partial "#{@current_stage}" %>
	
<%= end_form_tag %>

Your signup controller action could something similar to this:
  def signup
    case @request.method
      when :post
        @current_stage = @params['current_stage']
        if @current_stage == "stage1"
          @user.attributes = @params['user']    
            @current_stage = "stage2" if valid_for_attributes(@user,["login","attribute2"])
          end
        elsif @current_stage == "stage2"
          @user.attributes = @params['user']    
          @current_stage = "stage3" if valid_for_attributes(@user,["attribute3","attribute4"])
        elsif @current_stage == "stage3"
          @user.attributes = @params['user']
          
          if @user.save
            @session[:user] = User.authenticate(@user.login, @params['user']['password'])
            flash['notice']  = "Signup successful"
            redirect_to :action => "home"
          end
        end
      when :get
        @current_stage = "stage1"
    end
  end
                
                    
import e32
from SomeBigLibrary import *

e32.ao_yield()
# your codes follow
Series60 phones use cooperative multitasking.
You call e32.ao_yield() here and there to let other tasks run before they return back to you.

e32.ao_lock() also plays a role when you wait for callback.                
                    'C' is the built-in phone memory
'D' is a RAM disk
'E' is an extra memory card
'Z' is read-only ROM memory
                
                    
import key_codes
obj.bind(key_codes.EKeyNo, func)  # bind key "No" to a function
See a more detail example here.
http://discussion.forum.nokia.com/forum/showthread.php?threadid=58993                
                    
from appuifw import note

message = u"All's well"    # must be unicode , using u""
note(message, 'info')     # 'info' or 'error' or 'conf'

# info = information message box
# error = error message box
# conf = confirm message box