Never been to DZone Snippets 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

« Newer Snippets
Older Snippets »
Showing 11-20 of 24 total

helper to determine if radio/checkbox needs to be checked

I frequently have to use methods such as 'radio_button' and 'check_box_tag' when I don't have an object with a method that will automatically determine the value of the input field. Therefore, I have to check to see if a certain parameter has been passed, and if so, if the parameter's value matches that of the input's value. This method does that.

It's designed to be used in a Rails helper. You can either pass it the object, method, and value (the same parameters as, for example, radio_button) or name and value (the same parameters as radio_button_tag).

def checked?( *args )
  if args.length == 3
    object, method, value = args
    if params[object] && params[object][method] && params[object][method] == value
      'checked'
    end
  elsif args.length == 2
    name, value = args
    if params[name] && params[name] == value
      true
    end
  end
end


Here's an example usage:
<%= radio_button 'person', 'age', '12', :checked => checked?( 'person', 'age', '12' ) %>


If params[:person][:age] exists and it equals '12', then 'checked?' returns 'checked'; otherwise, it returns nil.

go from model to associated table name and back

Given a table object, it returns the related string object; e.g. SubAttribute => 'sub-attribute'. Useful if you want to make a list of all your tables with perhaps their fields listed out to the side.

def stringify_table( table, replace_char = '-', pluralize = false )
  string = table.to_s.gsub( /([A-Za-z])([A-Z])/, '\1' << replace_char.to_s << '\2' )
  string = string.pluralize if pluralize
  string
end


Given a string akin to the name of a table, it returns the related table object; e.g. 'sub_attributes' => SubAttribute.

def tablify_string( string )
  eval( string.to_s.gsub( /_id/, '' ).singularize.split( '_' ).collect { |word| word.capitalize }.join )
end

Object paternity

// object paternity in Javascript

// relationship of object 1 to object 2
function objectPaternity(obj1, obj2) {
 // given an object this function returns 'child' if obj1 is a child of obj2
 // and 'parent' if obj1 is a parent of obj2 - then 'no' if neither
 var relationship = 'no';
 var currentElement = obj1;
 
 while((typeof currentElement.parentNode != 'undefined') && (currentElement != document.body)) {
  // first cycle through all the parent elements of object 1 to see if object 2 is one of them
  if(currentElement.parentNode == obj2) {
   relationship = 'child';
  }
  // walk up the tree and try again
  currentElement = currentElement.parentNode;
 }
 // if object 1 is not a child of object 2 then we test the other way arround
 if(relationship == 'no') {
  currentElement = obj2;
  while((typeof currentElement.parentNode != 'undefined') && (currentElement != document.body)) {
   // now cycle through all the parent elements of object 2 to see if object 1 is one of them
   if(currentElement.parentNode == obj1) {
    relationship = 'parent';
   }
   // walk up the tree and try again
   currentElement = currentElement.parentNode;
  }
 }
 return relationship;
}

Collection of a bunch of named stuff

Taken from this recipe and its comments.
class bunch(dict):
    def __init__(self,**kw):
        dict.__init__(self,kw)
        self.__dict__.update(kw)

Usage is simple.
>>> o = bunch(a='A', b='B')
>>> o
{'a': 'A', 'b': 'B'}
>>> o.a
'A'
>>> o.b
'B'
>>> 

You can use it as both an object and dict.

classmethod and staticmethod

class K(object):

  # normal method (instance method)
  def method1(self):
    print 'obj.method1() becomes method1(obj)'

  # class method
  def method2(cls):
    print 'K.method2() becomes method2(K)'
  method2 = classmethod(method2)

  # static method
  def method3():
    print 'K.method3() become just method3()'
  method3 = staticmethod(method3)

obj = K()
obj.method1()
K.method2()
K.method3()

Old and new-style class

Old style class
class K:
  ...

New style class
class K(object):
  ...

Some features such as properties are only avaiable in new-style class.
Learn more about New-style class

spec-block-to-named-block

spec-block-to-named-block: func [
    "Change all set-words in a spec block to regular words."
    input [block!]
][
    input: copy input
    parse input [
        some [mark: set-word! any-type! (change mark to word! first mark)]
    ]
    input
]

money-bag object

REBOL []

money-bag: context [
    data: copy []

    insert: func [value [money!] /local found] [
        repeat i length? data [
            if (first value) = (first data/:i) [
                poke data i add data/:i value
                found: true
                break
            ]
        ]
        if not found [append data value]
    ]

    remove: func [value [money!] /local found] [
        repeat i length? data [
            if (first value) = (first data/:i) [
                poke data i subtract data/:i value
                found: true
                break
            ]
        ]
        if not found [alert "That denomination wasn't found in the bag"]
    ]

    ; no conversions yet.
    total: has [result] [
        result: 0
        foreach value data [result: result + second value]
        result
    ]

    show: does [probe data]
]

ins: func [val] [bag/insert val  bag/show]
rem: func [val] [bag/remove val  bag/show]

bag: make money-bag []
ins $100
ins USD$100
ins DEM$100
ins USD$200
rem $50
print bag/total

halt

Fix for nil object error in Rails test fixtures

If you're seeing errors like this when you run Rails tests:

# NoMethodError: You have a nil object when you didn't expect it!


You might need to edit test/test_helper.rb to make sure use_instantiated_fixtures is true:

self.use_instantiated_fixtures = true


Prior to 1.0, Rails automatically created instance variables out of fixtures. So if you had a fixture record named "foo", you could access it in your test as "@foo". As of 1.0, the default is to disable that feature, which breaks a lot of existing code. Mike Clark explains the change.

with function

; Sort of like VB's with statement.
with: func [object block] [
    if object [do bind/copy block in object 'self]
]
« Newer Snippets
Older Snippets »
Showing 11-20 of 24 total