Jquery Event Handlers – Pitfalls and Tips

Javascript / jQuery Event Handlers – A few Pitfalls and Tips

  • Always return true or false at the end of the handler; true to allow additional events to fire, false to stop event propogation. If you do not oh boy will you get very strange behavior. For example, in recent Firefox releases you will get an error thrown with HTTP status 0 and message “Error,” yep, that is all you get.
  • if you have mutiple elementa trigger the same event and the only difference is data ( for example a list of names where clicking posts the name ), write a handler based off of a CSS class selector. Do not create one handler per row or item using unique div IDs as the CSS selector – this eats browser memory quickly!
  • Save jQuery elements in function scoped variablea and chain events from them – doing $( “selector” ) calls for the same element over and over again is expensive time and memory wise and slows your code down.
Posted in UI | Tagged , | Leave a comment

Using Pry with Padrino

Using Pry with Padrino

Pry is a really powerful replacement for IRB – I love using it with Rails. I recently started working with Padrino and of course had to have it working there as well.

Pry will read and execute a .pryrc file that exists in the current directory as it boots – here is my Padrino specific .pryrc file – it boots your app just like you’d get in Rails using Pry:

`

load %{./config/boot.rb}
load %{./config/database.rb}
load %{./config/apps.rb}

require 'padrino-core/cli/console'
require 'padrino-core/cli/adapter'
require 'padrino-core/cli/base'
require 'padrino-core/cli/rake'
require 'padrino-core/cli/rake_tasks'

def app
  Padrino.application
end

def start( server = :puma )
  puts %{Type Ctrl-C to background server}
  Padrino.run! server: server
rescue Exception => e
  puts %{Problem starting server: #{ e.to_s }}
end

def stop
  puts %{Stopping server}
  threads = Thread.list
  threads.shift
  threads.each { |t| Thread.kill t }
end

def save_to( file, contents )
  File.open( file, %{w} ) { |f| f.puts contents }
end

`

Posted in Ruby | Leave a comment

Ruby on Rails 3.1 with Ruby 1.9.2 – speeding up rspec 2 (2.11) tests

After reading a number of posts on speeding up tests with Rails:
* http://www.skuunk.com/2012/05/speeding-up-rspec.html
* http://www.dixis.com/?p=553
* http://stackoverflow.com/questions/3663075/speeding-up-rspec-tests-in-a-large-rails-application
* http://www.rubyinside.com/careful-cutting-to-get-faster-rspec-runs-with-rails-5207.html
* http://highgroove.com/articles/2012/04/06/sane-rspec-config-for-clean,-and-slightly-faster,-specs.html
* http://blog.plataformatec.com.br/2011/12/three-tips-to-improve-the-performance-of-your-test-suite/
* https://makandracards.com/makandra/950-speed-up-rspec-by-deferring-garbage-collection
* http://kpumuk.info/ruby-on-rails/my-top-7-rspec-best-practices/

We implemented a combination of practices to reduce our test execution time from 15 minutes for 549 tests down to 7 minutes!:

* Implement the shared connection code to ensure Capybara and non-request tests share a database connection via spec/spec_helper.rb: http://kpumuk.info/ruby-on-rails/my-top-7-rspec-best-practices/

class ActiveRecord::Base
  mattr_accessor :shared_connection
  @@shared_connection = nil
  def self.connection
    @@shared_connection || retrieve_connection
  end
end

* Decrease logging from DEBUG to INFO in spec/spec_helper.rb – http://blog.plataformatec.com.br/2011/12/three-tips-to-improve-the-performance-of-your-test-suite/

 Rails.logger.level = 2

* Switch from rspec transactions to database_cleaner transactions in spec/spec_helper.rb – http://highgroove.com/articles/2012/04/06/sane-rspec-config-for-clean,-and-slightly-faster,-specs.htm. This change sped up test runs by over 30%!

  RSpec.configure do |config|

    config.before(:all) {
      DatabaseCleaner.strategy = :transaction
      DatabaseCleaner.clean_with(:truncation)
    }

    config.before(:each) {
      Rails.application.routes.default_url_options[:host] = %{example.com:80}
      DatabaseCleaner.start
    }

    config.after(:each) {
      DatabaseCleaner.clean
    }

Tried tweaking Ruby’s GC performance with 1.9.2 but couldn’t find settings that helped performance noticeably without starving the system of memory.

Posted in Ruby, Ruby on Rails | Leave a comment

Freezing ruby data structures recursively

Flavorrific published a monkey patch that extends Object with a deep freeze method that freezes child arrays and hashes of a data structure so that they aren’t accidentally changed (for example, configuration data from YAML).

I have extended his work in the following ways:

  • Attributes of child objects are frozen as well
  • Accesses to non-existent hash and array keys throw an IndexError.
class Object

 # Define a deep_freeze method in Object (based on code posted by flavorrific
 # http://flavoriffic.blogspot.com/2008/08/freezing-deep-ruby-data-structures.html)
 # that will call freeze on the top-level object instance the method is 
 # called on in as well as any child object instances contained in the
 # parent. This patch will also raise an IndexError if keys from    
 # ‘deeply frozen’ Hashes or Arrays are accessed that do not exist.

def deep_freeze

   #  String doesn’t support each
  if (self.class != String) && (self.respond_to? :each)
    each { |v|
      v.deep_freeze if v.respond_to?(:deep_freeze)
    }
  end

  #  Deep freeze instance variable values
  if self.kind_of? Object
    self.instance_variables.each { |v|
      iv = self.instance_variable_get(v)
      iv.deep_freeze
      self.instance_variable_set(v, iv)
    }
  end

  if self.kind_of? Hash
    instance_eval(<<-EOF)
      def default(key)
        raise IndexError, “Frozen hash: key ‘\#{key}’ does not exist!”
      end
    EOF
  end

  #  Prevent user from accessing array elements that do not exist.  
  if self.kind_of? Array
    instance_eval(<<-EOF)

      def at(index)
          self.fetch(index)
      end

      def [](arg1, arg2 = nil)

        results = Array.new

        if ! arg2.nil?
          #  Start index and end index given
          arg1.upto(arg1 + arg2) { |index|
            results << self.fetch(index)
          }
        else
          if arg1.kind_of? Range
            #  Range passed in
            arg1.each { |index|
              results << self.fetch(index)
            }
          else
            results << self.fetch(arg1)
          end

        end

        results

      end
    EOF

    end

    #  Freeze the current structure
    freeze

  end

end
Posted in Ruby | Leave a comment

Easy to use ruby library for interacting with Confluence – confluence4r

http://confluence.atlassian.com/display/DISC/Confluence4r

I added a gemspec for the package to the bottom of the page if you want to build it as a gem in-house.

— Max Schubert

Posted in Ruby | Leave a comment

Serialization of ActiveRecord model fields – let AR do it and avoid much pain – Ruby on Rails 3.0.9, Ruby 1.9.2

Created an ActiveRecord model that had a single field that would hold a data structure that included a non-AR object as a part of a Hash that I wanted serialized to the database and de-serialized on retrieval.

Remembering my java days, I wrote a getter and setter to override ActiveRecord’s default getter and setter to do the serialization / de-serialization:

def myfield=( data )
  write_attribute( :myfield, YAML::dump( data ) )
end

def myfield
  YAML::load read_attribute( :myfield )
end

Easy enough and worked fine on my OSX and our Linux-based pair programming environments.  Check into trunk, let Jenkins build it and deploy to our Linux-based CI environment and BOOM!  Serialization failures all over the place.

Went down a long road of switching between ‘syck’ and ‘psych’ for YAML and Marshal (which requires ASCII-8BIT encoding and causes all sorts of encoding pain) … nothing worked.

Finally, I came across the serialize macro for ActiveRecord (that is what I get for not reading the docs *first*), which marks a field for serialization.

class MyClass < ActiveRecord::Base
  serialize :myfield
end

Voila! Code works everywhere – good ActiveRecord magic.

Hope this experience helps others having issues with serialization and ActiveRecord.

Posted in Ruby on Rails | Leave a comment