Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Snippets For Beginners

ryecroft edited this page Dec 10, 2012 · 10 revisions

A page for useful code snippets for those familiar with ruby, but not Objective-C.

Remove diacritics from strings

This can be done very efficiently using Objective-C.

 framework 'foundation'
 class String
  def remove_diacritics
   NSString.alloc.initWithData(self.dataUsingEncoding(NSASCIIStringEncoding,
    allowLossyConversion:true),
    encoding:NSASCIIStringEncoding)
  end
 end

In action:

 >> "Cécile".remove_diacritics
 => "Cecile"

Efficiently empty an NSArrayController of its objects

Probably the most obvious way is to tell the array controller to remove its arrangedObjects:

 myArrayController.removeObjects(myArrayController.arrangedObjects)

but this can be slow when there are a lot of objects in it. Using an NSIndexSet to indicate which objects to ditch seems to be quicker:

 framework 'foundation'
 class NSArrayController
  def empty!
   range = NSMakeRange(0, self.arrangedObjects.count)
   self.removeObjectsAtArrangedObjectIndexes(NSIndexSet.indexSetWithIndexesInRange(range))
  end

  # a similar technique can be employed to remove the selected objects
  def remove_sel!
    index_set = selectionIndexes # returns an NSIndexSet
    self.removeObjectsAtArrangedObjectIndexes(index_set)
  end
 end

Show a confirmation dialog

Shows a confirmation dialog. Returns true if the user clicks "Yes" and false if they click "No".

#!/usr/local/bin/macruby
framework 'foundation'
framework 'cocoa'

# Shows a confirmation dialog.
# Returns true if the user clicks "Yes" and false if they click "No".
# alert_style is an integer from 0-2. This controls the icon displayed
# in the alert:
# 0 - NSWarningAlertStyle. The application's icon will be displayed.
# 1 - NSInformationalAlertStyle. Same as 0.
# 2 - NSCriticalAlertStyle. Displays a warning style icon.
def confirmation_dialog(msg="Are you sure?", title="", alert_style=nil)
  alert = NSAlert.alertWithMessageText(title,
                                       defaultButton:"No",
                                       alternateButton:"Yes",
                                       otherButton:nil,
                                       informativeTextWithFormat:msg)
  alert.alertStyle = alert_style if alert_style
  alert.runModal == 0 ? true : false
end

In action:

delete_all_data if confirmation_dialog("Are you sure?", "This will delete all of your data", 2)
Clone this wiki locally