Wednesday, July 23, 2014

Simple NullObject For Ruby

Sometimes you don't need something fancy

I love the Null Object pattern. Especially on the things I've been working on where it just needs to work despite errors in data. When you find these errors it's handy to grab a NullObject that will quack like you need. 

Avdi Grimm wrote a great library, naught. It's great when you have a lot of dependency injection. If you're only using it once or twice in your small library, it's probably overkill.

So here's a simple formula for putting in your own simple nullobjects.

class NullObject
  # You can instantiate a new NullObject with arbitrary methods by calling

  # Interactions.NullObject.new({method1: "outcome1"})

  # That will apply the method to the object

  def initialize(methods={})

    methods.each_pair do |k,v|

      define_singleton_method k do

        v

      end

    end

  end

end

Then all you have to do to call it is:

NullObject.new(method1: "Output")

And the key is the method name and the value is whatever you want it to output.
So something like:

def user
  creator || NullObject.new(name: "Jim", accounts: [])
end

Will let your nullobject do user.accounts and return an empty array. Yay you always get an array instead of a NilClass error.

Friday, July 11, 2014

Homebrew MariaDB (MySQL) and strict_all_tables

I recently updated my MariaDB on OSX using homebrew and suddenly my tests were failing with a mysql error for inserting nulls. After some quick research I found that in a recent update MySQL and MariaDB defaulted sql_mode to strict_all_tables. This prevents nulls from entering where they were allowed before.

Ideally that option is what you would want, but in our case our app has been running for years with NULLs everywhere. It would break our application and was in fact doing so in development.

After some reasearch I found that by putting

[mysqld]
sql_mode=""

would disable it globally but was insufficient because running

SELECT @@SESSION.sql_mode;

would return STRICT_ALL_TABLES. Meaning that the database was still not functioning as before.

There's probably a better way, but how I fixed it was to modify the plist.
~/Library/LaunchAgents/homebrew.mxcl.mariadb.plist
and added:

<string>--sql-mode=</string>

to the program parameters.

Edit: I finally figured out why that session was being set in my rails application by a default.

In your database.yml file you'll want to add strict: false

It just so happened that I had upgraded maria and rails at the same time. Leading me to have a false positive. The plist option only appeared to work. After running tests a few more times the tests were failing again.