header image

page2

Extending Hash with Except and Only

I first saw this on the RSpec lists, but I can’t find who to originally credit. This little extension to Hash lets you easily get only the key(s) you want out of a hash, or all but certain keys out of the hash.

 1 class Hash
 2   # Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3}
 3   def except(*keys)
 4     self.reject { |k,v|
 5       keys.include? k.to_sym
 6     }
 7   end
 8
 9   # Usage { :a => 1, :b => 2, :c => 3}.only(:a) -> {:a => 1}
10   def only(*keys)
11     self.dup.reject { |k,v|
12       !keys.include? k.to_sym
13     }
14   end
15 end

 

Language: Ruby / Tags: hash / Posted by: spicycode / On: February 12th, 2007

Paginating an Array/Enumerable

Source: http://www.railsonwave.com/railsonwave/2007/1/24/howto-paginate-an-array

 1 def paginate_collection(collection, options = {})
 2     default_options = {:per_page => 10, :page => 1}
 3     options = default_options.merge options
 4 
 5     pages = Paginator.new self, collection.size, options[:per_page], options[:page]
 6     first = pages.current.offset
 7     last = [first + options[:per_page], collection.size].min
 8     slice = collection[first...last]
 9     return [pages, slice]
10   end

Language: Ruby / Tags: pagination, array, enumerable / Posted by: spicycode / On: January 27th, 2007

InvisibleScroller

 1 import mx.transitions.OnEnterFrameBeacon;
 2 
 3 /**
 4  * A scroller class with no visible interface
 5  * Uses masked area to calculate position
 6  */
 7 class com.orazal.tools.InvisibleScroller {
 8         // Enter Frame Beacon
 9         static var __initBeacon = OnEnterFrameBeacon.init();
10         // Target Clips
11         private var mask:MovieClip;
12         private var masked:MovieClip;
13         // Properties
14         private var dir:String = "vertical";
15         private var offset:Object;
16         private var oPos:Object;
17         private var newPos:Number;
18         private var easing:Number = 5;
19         
20         // Constructor
21         public function InvisibleScroller(dire:String, mask_mc:MovieClip, masked_mc:MovieClip) {
22                 dir = dire;
23                 mask = mask_mc;
24                 masked = masked_mc;
25                 // Store original masked positions
26                 oPos = {x:masked_mc._x, y:masked_mc._y};
27                 offset = {x:mask._x - masked._x , y:masked._y - mask._y};
28                 // Start listening to mouse
29                 Mouse.addListener(this);
30                 // EnterFrame listener
31                 MovieClip.addListener(this);
32         }
33         
34         /**
35          * Allows to change easing
36          */
37         public function setEasing(amount):Void{
38                 easing = amount;
39         }
40         
41         /**
42          * Enter Frame
43          */
44         private function onEnterFrame():Void {
45                 if(dir == "vertical"){
46                                 masked._y  += (newPos - masked._y )/ easing;
47                 }
48                 if(dir == "horizontal"){
49                                 masked._x  += (newPos - masked._x )/ easing;
50                 }
51         }
52         
53         /**
54          * Mouse listener
55          */
56         private function onMouseMove() {
57                 var point:Object = {x:_root._xmouse, y:_root._ymouse};
58                  mask.globalToLocal(point); 
59                 if(this.dir == "vertical"){
60                         var percent:Number = point.y/mask._height;
61                         var maskedTotal = offset.y + this.masked._height + 20
62                         var max:Number = maskedTotal - this.mask._height ;
63                         if(percent >= 0 && percent<=1){
64                                 newPos =(-max*percent ) + oPos.y ;
65                         }
66                 }
67                 if(this.dir == "horizontal"){
68                         var percent:Number = point.x/mask._width;
69                         var maskedTotal = offset.x + this.masked._width + 20;
70                         var max:Number =  maskedTotal - this.mask._width ;
71                         if(percent >= 0 && percent<=1){
72                                 newPos =(-max*percent ) + oPos.x;
73                         }
74                 }
75                         
76                 
77         };
78         
79         public function destroy():Void{
80                 MovieClip.removeListener(this);
81                 Mouse.removeListener(this);
82                 delete this;
83         }
84 }

Language: ActionScript / Tags: actionscript, scroller / Posted by: orazal / On: January 19th, 2007

CleanTags in VBA

Source: http://www.DanFM.us

 1 Function CleanTags(StringVal As Variant) As String
 2     
 3     On Local Error Resume Next
 4     
 5     Dim i As Integer
 6     Dim WorkString As String
 7     Dim workstring1 As String
 8     Dim workstring2 As String
 9     
10     Dim Buffer As String
11     
12     
13     Const OpenBrac = "<"
14     Const CloseBrac = ">"
15     
16     Dim TagStart As Integer
17     Dim TagEnd As Integer
18     Dim a
19     
20     Dim TagOn As Boolean: TagOn = False
21 
22     
23     If Len(Trim(StringVal)) = 0 Then Exit Function ' this is an empty string
24     
25     'for each letter
26     For i = 1 To Len(StringVal)
27         
28         
29         a = Mid(StringVal, i, 1)   'examine string
30         
31         Select Case a
32             
33              Case OpenBrac 'Is this character an open bracket?
34                 If TagOn = False Then
35                     TagOn = True  'Toggle this is a tag
36                     TagStart = i
37                 End If
38         
39             Case CloseBrac
40                 If TagOn = True Then
41                     TagOn = False  'Turn off tag toggle
42                     TagEnd = i
43                 End If
44     
45         End Select
46      
47      
48 'copy character for character, but dont copy if Tag Toggle is on.  Quickest way to do it.
49      If TagOn = False Then _
50         If (a <> ">") And (a <> "<") Then _
51         Buffer = Buffer & a  
52             
53             
54             
55     Next i
56     
57     
58 CleanTags = Buffer 'Return the clean string 
59 
60 End Function

Language: VbScript / Tags: vbscript, vba, excel, office, strings / Posted by: DanFM / On: January 16th, 2007
 

CleanTages


Source: www.danfm.us
Function CleanTags(StringVal As Variant) As String On Local Error Resume Next Dim i As Integer Dim WorkString As String Dim workstring1 As String Dim workstring2 As String Dim Buffer As String Const OpenBrac = "<" Const CloseBrac = ">" Dim TagStart As Integer Dim TagEnd As Integer Dim a Dim TagOn As Boolean: TagOn = False If Len(Trim(StringVal)) = 0 Then Exit Function ' this is an empty string 'for each letter For i = 1 To Len(StringVal) a = Mid(StringVal, i, 1) 'examine string Select Case a Case OpenBrac 'Is this character an open bracket? If TagOn = False Then TagOn = True 'Toggle this is a tag TagStart = i End If Case CloseBrac If TagOn = True Then TagOn = False 'Turn off tag toggle TagEnd = i End If End Select 'copy character for character, but dont copy if Tag Toggle is on. Quickest way to do it. If TagOn = False Then _ If (a <> ">") And (a <> "<") Then _ Buffer = Buffer & a Next i CleanTags = Buffer 'Return the clean string End Function

Language: VbScript / Tags: vbs, vbscript, excel, office / Posted by: DanFM / On: January 16th, 2007
 

URL validation

1 validates_format_of :company_url, :with => /((http|https):\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?)/

Language: Ruby / Tags: rails, regex, url, validation / Posted by: tfwright / On: January 3rd, 2007

 

Encrypted database passwords in database.yml

Source: http://skwp.wordpress.com/2006/08/28/encrypted-db-passwords-for-rails-with-databaseyml-and-erb/

Some people are upset that database.yml can expose passwords in plaintext. However, there is a pretty simple way to get encryption into database.yml. Because the database.yml file is actually run through an ERB interpreter by Rails, we can put code into our file:

1 # database.yml
2 production:
3   adapter: mysql
4   username: db_user
5   password: <%= custom_method_to_obtain_password %>
6   host: your_db_host

Language: Ruby / Tags: rails, activerecord, erb / Posted by: spicycode / On: January 1st, 2007

Managing database.yml with capistrano

Source: http://www.jvoorhis.com/articles/2006/07/07/managing-database-yml-with-capistrano

Here is the code that lets us write our database.yml after we deploy, and then symlinks it correctly:

 1 desc "Create database.yml in shared/config" 
 2 task :after_setup do
 3   database_configuration = render :template => <<-EOF
 4 login: &login
 5   adapter: postgresql
 6   host: localhost
 7   port: <%= postgresql_port %>
 8   username: <%= user %>
 9   password: <%= password %>
10 
11 development:
12   database: <%= "#{application}_development" %>
13   <<: *login
14 
15 test:
16   database: <%= "#{application}_test" %>
17   <<: *login
18 
19 production:
20   database: <%= "#{application}_production" %>
21   <<: *login
22 EOF
23 
24   run "mkdir -p #{deploy_to}/#{shared_dir}/config" 
25   put database_configuration, "#{deploy_to}/#{shared_dir}/config/database.yml" 
26 end
27 
28 desc "Link in the production database.yml" 
29 task :after_update_code do
30   run "ln -nfs #{deploy_to}/#{shared_dir}/config/database.yml #{release_path}/config/database.yml" 
31 end

Language: Ruby / Tags: rails, capistrano / Posted by: spicycode / On: January 1st, 2007

Reloading controllers and models

Source: http://www.ryandaigle.com/articles/2006/06/02/note-to-self-reloading-my-rails-app-within-the-console

In script/console simply do:

1 reload!

Language: Ruby / Tags: rails / Posted by: spicycode / On: December 31st, 2006

Tail your logs with capistrano

Source: http://www.clarkware.com/cgi/blosxom/2006/08/30#NewCapistranoGoodies

1 task :tail_log, :roles => :app do
2   stream "tail -f #{shared_path}/log/production.log"
3 end

Language: Ruby / Tags: rails, capistrano, logging / Posted by: spicycode / On: December 31st, 2006