Topics: Ruby

External content

Aspect Oriented Programming in Ruby

Slides presenting ways to integrate the ideas of Aspect-Oriented Programming in Ruby.

Outline

  • Why Aspect-Oriented Programming?
  • AOP in Java and AspectJ (a Review).
  • AOP in Ruby.
    • What you can do today.
    • Example AOP-isms in Ruby on Rails.
  • Aspect-Oriented Design.
  • The AOP Promise for Tomorrow.
External content

Ruby blocks: Braces and do/end have different precedence

Braces and do/end are completely swappable—almost all the time. They have different precedence. It’s not often that anyone comes across what this means in practice.

Fix [RubyODBC]Cannot allocate SQLHENV when connecting to MSSQL 2005 with Ruby 1.8.7. on Ubuntu 10.10

I followed this nice guide Connecting to MSSQL with Ruby on Ubuntu - lambie.org until I ran in the following errors:

irb(main):001:0> require "dbi"; dbh = DBI.connect('dbi:ODBC:MyLegacyServer', 'my_name', 'my_password')

DBI::DatabaseError: INTERN (0) [RubyODBC]Cannot allocate SQLHENV
  from /usr/lib/ruby/1.8/dbd/odbc/driver.rb:36:in `connect'
  from /usr/lib/ruby/1.8/dbi/handles/driver.rb:33:in `connect'
  from /usr/lib/ruby...

Setup or update Passenger to use Ruby Enterprise

  1. Your current ruby must be Ruby Enterprise.
  2. gem install passenger
  3. passenger-install-apache2-module
  4. Edit your httpd.conf according to the instructions provided at the end of the setup script.
  5. Restart Apache: sudo service apache2 restart

This also works when you previously ran your Passenger using MRI. Just run the setup as described.

RubyMine: Find and execute a menu action by its name

You are looking for a functionality in RubyMine but don't know or remember its keyboard shortcut or which menu it is located in?
Hit Ctrl+Shift+A.

This will bring up the "Find Action" box where you can enter an action's name or category. Pick the result from the list to run it.

The list of results will also show you any assigned keyboard shortcuts.

Ruby: Indent a string

Copy the attached file to config/initializers/indent_string.rb and you can say

"foo".indent(4) # "    foo"

Note you will find many simpler implementations of this method on the Interweb. They probably won't do what you want in edge cases, fuck up trailing whitespace, etc. The implementation in this card has the following behavior:

describe '#indent' do

  it 'should indent the string by the given number of spaces' do
    "foo".indent(2).should == "  foo"
  end

  it 'should indent multiple lines line by line' do

How to fix: RubyMine does not remember last used monitor (on Ubuntu)

Every time I started RubyMine, it opened the main window on the left monitor – when moving it to the center monitor and closing it, the next time it still opened up on the left one.

Here is how I forced RubyMine to start up on a different screen:

  1. Un-maximize the main window
  2. Move it to your preferred monitor
  3. Close RubyMine (keep it unmaximized)
  4. Start RubyMine again.
  5. You may now maximize your main window; the next time you start up RubyMine, it will open on the correct screen, maximized.

That's crazy!

Ruby: Find the most common string from an array

This will give you the string that appears most often in an array:

names = %w[ foo foo bar bar bar baz ]
names.group_by(&:to_s).values.max_by(&:size).try(:first)
=> "bar"

This is very similar to the linked StackOverflow thread, but does not break on empty arrays.

Note that try is provided by ActiveSupport (Rails). You could explicitly load activesupport or use andand on plain Ruby.

External content

Ruby, Ruby on Rails, and _why: The disappearance of one of the world’s most beloved computer programmers

Nice article to educate your non-geek girlfriend/boyfriend about the joys of programming.

RubyMine: Disable window animations

Under Settings / Appearance you can uncheck a box Animate windows. This will change your life.

RubyMine: Exclude data and log directories from a project

RubyMine offers you to exclude directories from search, meaning faster search results and less "noise" in the list of result.

Right-click a folder in your project tree and click "Mark Directory As" → "Excluded".

Do it for your your log, data, and other directories that you don't need to access during development and whose search results are irrelevant.
They won't be deleted but simply ignored when searching across a project's files.

Use the "retry" keyword to process a piece of Ruby code again.

Imagine you have a piece of code that tries to send a request to a remote server. Now the server is temporarily not available and raises an exception. In order to re-send the request you could use the following snippet:

def remote_request
  begin
    response = RestClient.get my_request_url
  rescue RestClient::ResourceNotFound => error
    @retries ||= 0
    if @retries < @max_retries
      @retries += 1
      retry
    else
      raise error
    end
  end
  response
end

This sni…

Convert primitive Ruby structures into Javascript

Controller responses often include Javascript code that contains values from Ruby variables. E.g. you want to call a Javascript function foo(...) with the argument stored in the Ruby variable @foo. You can do this by using ERB tags (<%= ruby_expression %>) or, in Haml, interpolation syntax (#{ruby_expression}).

In any case you will take care of proper quoting and escaping of quotes, line feeds, etc. A convenient way to do this is to use Object#json, which is defined for Ruby strings, numb…

Capybara: Test that a string is visible as static text

This is surprisingly difficult when there is a <textarea> with the same text on the page, but you really want to see the letters as static text in a <p> or similiar.

The step definition below lets you say:

Then I should see the text "foo"

You should not look too closely at the step definition because when you see the light, it will blind you.

Then /^I should see the text "(.*?)"$/ do |text|
  elements = page.all('*', :text => text).reject { |element| element.tag_name == 'textarea' || element.all('*', :text => text...

Compare two XML strings as hashes

Let's say you have two XML strings that are ordered differently but you don't care about the order of attributes inside containers:

a = '<?xml version="1.0" encoding="UTF-8"?><Authenticate><User>batman</User><Password>secret</Password></Authenticate>'
b = '<?xml version="1.0" encoding="UTF-8"?><Authenticate><Password>secret</Password><User>batman</User></Authenticate>'

Working with plain string comparison is not helpful, of course:

a == b
=> false

Instead, you can use the Nori gem …

Fix YAML::Syck::DefaultKey:0x1083b59f8

When your gems complain about invalid gemspecs and illformed requirements, it is most probably an error resulting from the transition from Syck to psych. To fix this:

  1. go to your gemspec directory (e.g. /Library/Ruby/Gems/1.8/specifications/)
  2. change #<Syck::DefaultKey:0x00000100e779e8> to = (equals sign) in each file that's complaining

Associations named using a string cannot be included in a scope

If you defined your association via

class Article
  belongs_to "category"
end

and you try

Article.scoped(:include => :category)

you will get an error message

in `preload_one_association': Association named 'category' was not found; perhaps you misspelled it? (ActiveRecord::ConfigurationError)

Solution

Always define your assocations via symbol

class Article
  belongs_to :category
end  
403 cards