0

Changing Default Column Values

Posted by garrinmf on February 25, 2011 in Ruby

A note to self so I remember when next I need this:

First, I don't want to wade into the argument about where default values should, in the database or in the code (see this and this for example).

I left a default value off of a number of fields when I first created them and now I wish that I hadn't. I found absolutely nothing in the guides on changing defaults and googling turned up nothing as well. Finally digging through the documentation on ActiveRecord migrations I turned up paydirt.

http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html#method-i-change_default

RUBY:
  1. t.change_default(:qualification, 'new')
  2. t.change_default(:authorized, 1)

or a more complete example

RUBY:
  1. def self.up
  2.   change_table users do |o|
  3.     o.change_default :active, true
  4.   end
  5. end

Tags:

2

Starting Ruby on Rails: what platform…

Posted by garrinmf on February 3, 2011 in Meanderings, Ruby

Notice: I understand this is nearing religious boundaries, these are just my feelings from my experience..

I've been playing around with Ruby on Rails (RoR) for sometime now on the side, looking to get to know it so any 'new' projects at work can utilize it's goodness. The reason for this could be a whole other post, but for time sake we'll just say that for the last couple years on a PHP/Zend project I've found myself striving to implement things that RoR rails provides out of the box. The following is just my experience in learning RoR.

    Windows 7

In my playing I started out on my Windows 7 based desktop and the Windows 7 install on my dual-boot laptop as this was what I was in most of the time for work. My dev environment was pretty simple:

  • Windows
  • Emacs 23.?
  • Multiple modes, flymake, ecb, other emacs goodness
  • git bash (as a terminal)
  • Ruby 1.9.2 w/Devkit (rubyinstsaller.org)
  • Rails 3 w/ various gems

I will say that it was easy to setup on Windows, no problems there. Some issues that I accounted to Windows were actually issues with most tutorials still being Rails2 at the time and the inclusion of bundler and the need for bundle exec in Rails3.

The reason I would NOT recommend Windows for Rails development is SPEED. If I'd gotten into more depth as far as gems and such it sounds like there might have been compatibility issues as well but I stopped well short of that due to speed. Running 10 unit tests (rspec) would take as much as 30 seconds OR MORE on Windows. Those same tests on other platforms would take less 5 seconds or less depending on circumstances. Starting console or server was just as painfully slow. I'm running an i7 quad core with 6gb of RAM, so it's not like it was the machine lacking; it's the most powerful of all 3 machines.

The other negative was no RVM on Windows. I don't jump ruby versions much but having separate gemsets has turned out to be awesome. I've since heard of a windows copy called pik, but I can't vouch for it.

    OSX

I also have a mac mini at my desk for previous projects I've done for iPhone apps. Setting up my 'standard' environment in OSX was actually somewhat of a problem. Turns out that a number of the tools I use are baked into OSX and either upgrading them or replacing them is near impossible. Luckily, as it seems OSX is the platform of choice for RoR development, most of these problems have been overcome. One such tool is RVM. It's an awesome tool in itself but it's almost required on OSX if you want to use anything beyond the OSX baked in ruby 1.8.7 from 2009.

Once up and running OSX performed VERY nicely, especially after coming off of the very slow Windows. Having a better command line and more/better tools there is a definite plus as well.

Another negative that I've since found deals with the MacBook Pro and it's keyboard layout. I setup my dev environment on my wife's MBP and I find it very trying. If you're an emacs user Ctrl & Alt are more important than the home row to you and your coding. Well, on the MBP, they put the FN key out there where every other keyboard I've used puts the Ctrl key and it is MESSING with me. I've tried getting used to it but can't. Fortunately I think you can remap the keyboard, if I could only talk my wife into it...

    Ubuntu

My laptop has 2 hdd's and currently it's setup to dual boot between Windows 7 on one drive and Ubuntu Linux on the other drive. I think this is going to change to be a full Ubuntu install with a VM of windows on the second drive very soon. Setup was much the same as on windows: Emacs, Rails 3, Rails 1.9, etc. The only addition was RVM as with the OSX.

I'd definitely recommend Ubuntu (or linux) for a development environment for Ruby. Easy to install and setup. Very speedy (compared to windows) for running tests, console, and server. Linux in general can have some problems from time to time. Being all open, sometimes things just don't work as nicely together as you'd want. But it tends to give you may more flexibility.

    Conclusion
  1. Ubuntu (Linux)
  2. OSX
  3. Windows

Windows would be the one 'do not recommend'. It's doable but painful! The other two have there problems but Ubuntu wins for two reasons: I like Linux, and it's almost certainly what your app is going to be running on in production anyways! Also, OSX has a rather high barrier to entry (cost), while Ubuntu has become almost stupidly simple to install and the inclusion of an 'App Store' makes getting all the big stuff together a breeze. Plus you can try it out inside a VM (like VirtualBox) in like an hour or two for free.

Granted, my post is based off a number of assumptions like using Emacs for an IDE. If I was a TextMate user I'd almost be forced to use OSX. I'd guess there are F/OSS editors that have tried to mimic TextMate you could get on Linux but TextMate itself is OSX.

From Left to Right: Mac Mini (2 screens), Windows 7 desktop, Dual-Boot laptop

But you don't have to take my word for it!
--
Mark

Tags: ,

0

errors with mysql gem on win x64

Posted by garrinmf on February 10, 2010 in Coding, Ruby

Quick information post here. While searching on this issue I saw lots of posts with "I uninstalled the mysql 64-bit version and installed the 32-bit version to make this work".

It doesn't have to be like that. Ruby doesn't care in the slightest what version of mysql it's talking to, it does so over mediums that are universal.

According to your PATH environment variable part of installing the ruby mysql gem is to add 'mysql/bin' to your PATH or to copy the libmysql.dll to 'ruby/bin'. If you don't you get errors like 'The specified module could not be found'. If you do this and you're running mysql for x64 then you can potentially get errors about '%1 is not a valid Win32 application'.

Having had very similar issues with the native libraries and a .NET program, I know that things can't get weird. I'm going to guess that, like me, you installed a 32-bit version of Ruby, so it gets run in some compatibility mode for 32-bit programs, and all things it directly interacts with (loads), need to be 32-bit. Since you copied a 64-bit version of libmysql.dll it's not happy. Simply copy a libmysql.dll from a 32-bit installation, I happened to have a 32-bit laptop with mysql installed laying around, and all should work fine.

It can get even more confusing with .NET because if you build your app when choosing the 'x86' platform, it works like mentioned above with everything always needing to be 32-bit. If you compile it with 'any cpu' selected for the platform it depends on the machine; if it's 64-bit you need 64-bit things and if it's 32-bit you need 32-bit.

Tags: ,

0

Fighting with XML Deserialization

Posted by garrinmf on November 19, 2009 in Coding, CSharp, Databases

Hopefully somebody comes back in the comments with a better solution, as this feels dirty to me, but for someone else looking for "a" method here is what I came up with.

The scenario:
There is this XML document that is already specified and utilized throughout an entire system that contains a Person object. In the persistence framework the coder initially took the lazy route and stored the large binary data for the picture right in row with the rest of the Person data. The class looked something like this:

C#:
  1. public class Person
  2. {
  3.      // fields...
  4.      
  5.      public virtual byte[] Picture
  6.      {
  7.           get;
  8.           set;
  9.      }
  10.      // more properties and other gooey goodness...
  11. }

All was well and good until the system was under any amount of load and the huge image was getting loaded into memory whenever the row was loaded. The OR/M of choice didn't support lazy property loading and the best long term solution, in any case, was to move the column to it's own table. Moving into the filesystem, while another choice that was possibly better, wasn't an option.

So a little coding later, the picture byte[] data was moved into it's own subcomponent / child object, the OR/M of choice was tweaked to lazy load that particular object via proxy and that left something like this

C#:
  1. public class Person
  2. {
  3.      // fields...
  4.      
  5.      public virtual BinaryData Picture
  6.      {
  7.           get;
  8.           set;
  9.      }
  10.      // more properties and other gooey goodness...
  11. }
  12.  
  13. public class BinaryData
  14. {
  15.      public virtual ulong Id
  16.      {
  17.           get;
  18.           set;
  19.      }
  20.  
  21.      public virtual byte[] Data
  22.      {
  23.           get;
  24.           set;
  25.      }
  26.      // other gooey goodness...
  27. }

Easy fix in the persistence side of things, simple refactoring, and you're off and saving your blobs in a much more performance friendly manner. Except that your simple "XmlSerializer.Deserialize" call is now failing because your Person object now has a different structure that doesn't match the XML.

After much googling, documentation reading, and hand pounding no solution was found. All kinds of tricks for renaming properties in XML, making properties attributes, and otherwise effecting the XML but nothing in affecting the mapping of one 'level' of the hierarchy to another. Only fix found, was to essentially catch an exception which is never good. On the XmlSerializer object there was a "UnknownElement" event that gets fired when unknown elements are found that don't map to a property.

Final Solution:

C#:
  1. public class Person
  2. {
  3.      // fields...
  4.      
  5.      [XmlIgnore]
  6.      public virtual BinaryData Picture
  7.      {
  8.           get;
  9.           set;
  10.      }
  11.      // more properties and other gooey goodness...
  12. }
  13.  
  14. public class BinaryData
  15. {
  16.      public virtual ulong Id
  17.      {
  18.           get;
  19.           set;
  20.      }
  21.  
  22.      public virtual byte[] Data
  23.      {
  24.           get;
  25.           set;
  26.      }
  27.      // other gooey goodness...
  28. }
  29.  
  30. // elsewhere in the deserializer.UnknownElement event handler
  31. private void serializer_UnknownElement(object sender, XmlElementEventArgs e)
  32. {
  33.     if (e.Element.Name == "Picture")
  34.         (e.ObjectBeingDeserialized as Person).Picture.Data = (Convert.FromBase64String(e.Element.InnerText));
  35. }

Note: This does work if you are deserializing a list of Person objects as well. The e.ObjectBeingDeserialized property is set to the Person object at the time of the event, not the collection that is eventually returned.

Tags: , ,

0

Auto Reload – Without TMP

Posted by garrinmf on November 2, 2009 in Tools, Uncategorized

I've tried a couple of times to "move away" from Firefox as my main browser mainly to see changes in memory usage and also to check out other browsers "features". The show stopper? AutoReload provided by Tab Mix Plus (TMP) in Firefox. There are 2-3 pages that I want to continually refresh for work and I could never find the equivalent in other browsers. That is, until now! I'm typing this in Chrome and have been happily using chrome for the last 2-3 days.

Supposedly this works in any browser including Firefox if you don't want to utilize TMP, which I think was a major source of my memory issues with TMP keeping not only the history for the 30 tabs I have open but the 10 tabs I last had opened.

javascript: timeout=prompt("Set timeout [s]"); current=location.href; if(timeout>0) setTimeout('reload()',1000*timeout); else location.replace(current); function reload(){ setTimeout('reload()',1000*timeout); fr4me='<frameset cols=\'*\'>\n<frame src=\''+current+'\'/>'; fr4me+='</frameset>'; with(document){write(fr4me);void(close())}; }

Just create a bookmark with the given code and then while on the page you want to reload, click the bookmark from your toolbar. It'll ask you how often you want to reload (in seconds) and it starts reloading!

0

SRP/SoC all the way

Posted by garrinmf on November 2, 2009 in Coding, CSharp, Meanderings

The last couple of months I've been fighting some pain with utilizing IoC, scoping the lifecycle of an object based on another object. So the singleton pattern, but only under a given object, i.e. all objects under a given presenter that request a certain service get the same service. Pretty much every IoC out there has full support for web based scoping paradigms and most have a "per thread" scoping but none, AFAIK, support the object approach.

I realize I'm still just an apprentice, so I did some digging before I just assumed that everybody else was wrong and just implemented it myself (most IoC containers do support some sort of custom scoping).

What I realized was I hadn't "really" pulled off good SRP/SoC, or at least I hadn't refactored after moving to good SRP/SoC. Please realize, this is a made up story to reproduce the given problem, not all decisions are the "right" ones, they're the ones that get me where I want to go with this!

    The Story


One day our customer said that they needed to be able to determine the distance any one of their Customers was away from given coordinates. So I got in and added a quick little method and viola!

C#:
  1. public class Customer
  2. {
  3.      private GPSCoord _location;
  4.      ......
  5.      public decimal DistanceFromCoordinates(GPSCoord coords)
  6.      {
  7.            // figure out the distance
  8.            return distance;
  9.      }
  10.      ......
  11. }

Couple of months later, the customer said they needed to be able to choose between the distance being in Metric or Imperial on an installation basis. So, good guy that I am, I decided that a customer shouldn't change if the way we measured things changed so I pulled out the code and added a parameter to the Customer that took in an IDistanceService. All was well, things were separated, my IoC container of choice was loading the proper measurer and my Customer object didn't know the difference!

C#:
  1. public class Customer
  2. {
  3.      private GPSCoord _location;
  4.      private IDistanceService _distService;
  5.      ......
  6.      public Customer(...., IDistanceService distService)
  7.      {
  8.            _distService = distService;
  9.      }
  10.      ......
  11.      public decimal DistanceFromCoordinates(GPSCoord coords)
  12.      {
  13.            return _distService.DistanceBetween(_location, coords);
  14.      }
  15. }

Now, the customer came back ANOTHER time (starting to sound familiar?) and said that they also needed to be able measure distances between two other, arbitrary items, and that the change between Metric/Imperial would be on a per Order basis, not installation. Not a problem says I, I already have my pretty IDistanceService , I can just add it as a parameter on said arbitrary item and it can measure away! And changing the implementation of IDistanceService per order, not a problem! I'll just scope per object. But wait, I don't have that ability in my IoC. Eh, it's the right way to do it, I'll just make sure my Order gets the right impl and do some manual dependency injection myself!!!

Just days after I push out the updates, the customer starts coming back to me with all kinds of weird issues. Orders having the right measurement system when opened but coming back to them they have the wrong one. Improper systems completely. I have no idea! I didn't duplicate any code, i followed all kinds of good things from the programmers "Alphabet Soup"; SRP/SoC/IoC/DIP/ISP!! How did I miss somewhere that the configuration was getting setup!?

After researching/discussing/looking I found the answer. It was subtle, but major. I had duplicate code all over the place. It's just, that in this case, the duplicate code wasn't actual code, but duplicate dependencies. When I said that the Customer shouldn't know about changes in how to MeasureDistances, what I should have said was that the Customer shouldn't know how to measure AT ALL!! Separating concerns, in this case, wasn't enough. I needed to centralize concerns as well. After pulling the dependencies out of the classes and centralizing the code to remove duplication, I needed to pull that dependency "up the stack" to a higher level in order to remove "dependency duplication". All of the individual references to the IDistanceService had turned into a nightmare to manage and update and they didn't need to be there. Let the object that was asking for the measurement reference the IDistanceService, not the items being measured!!

C#:
  1. public class Customer
  2. {
  3.      private GPSCoord _location;
  4.      ......
  5.      public GPSCoord Location
  6.      {
  7.            get{...};
  8.            set{...};
  9.      }
  10. }
  11.  
  12. public class OrderPresenter : IPresenter
  13. {
  14.      //  Anywhere a distance needs to be presented under this Order/OrderPresenter, utilize this IDistancePresenter!
  15.      public OrderPresenter(IDistanceService distService, ...)
  16.      {
  17.           ....
  18.      }
  19. }

    The End!

Moral of the story, if something doesn't exist in any current framework, there's probably a reason!!

0

A good argument for Fluent NHibernate…

Posted by garrinmf on June 5, 2009 in Coding, CSharp, External Blogs, NHibernate

Here is a good reason to use Fluent NHibernate. Don't give me this stuff about xml being hard and not everybody understands it, because I don't buy that. Give me things like it's more testable, refactorable, and you get build-time feedback.

Now if only I had the time to bring my current project up to speed and add this. Hopefully at some point. Anybody know of a current list of "known issues" or "lacking areas" of the mapping that you can only do in XML still?

0

Caliburn, Silverlight IsolatedStorage, and another reason to use a framework…

Posted by garrinmf on June 4, 2009 in Coding, CSharp, Tools

My current project is a Silverlight Application and I've been utilizing the Caliburn Framework from the beginning for a number of useful things is it does with binding and implementing an MVP/MVVM model in SL.

Today I needed to utilize the IsolatedStorage feature of Silverlight to start saving some per-user settings for the app. I remember having read something about it in the Caliburn docs and 5 minutes later I was up and running.

Example Usage From their LOB Example:

C#:
  1. public class Settings : IsolatedStorageStateManager, ISettings
  2.     {
  3.         private const string _fileName = "Settings.xml";
  4.  
  5.         public Settings()
  6.         {
  7.             AfterStateLoad += delegate { NotifyOfPropertyChange(""); };
  8.         }
  9.  
  10.         public TimeSpan EarliestAppointment
  11.         {
  12.             get
  13.             {
  14.                 var milliseconds = Get("EarliestAppointment", TimeSpan.FromHours(9).TotalMilliseconds);
  15.                 return TimeSpan.FromMilliseconds(milliseconds);
  16.             }
  17.             set
  18.             {
  19.                 InsertOrUpdate("EarliestAppointment", value.TotalMilliseconds.ToString());
  20.                 NotifyOfPropertyChange("EarliestAppointment");
  21.             }
  22.         }
  23.  
  24.         public TimeSpan LatestAppointment
  25.         {
  26.             get
  27.             {
  28.                 var milliseconds = Get("LatestAppointment", TimeSpan.FromHours(17).TotalMilliseconds);
  29.                 return TimeSpan.FromMilliseconds(milliseconds);
  30.             }
  31.             set
  32.             {
  33.                 InsertOrUpdate("LatestAppointment", value.TotalMilliseconds.ToString());
  34.                 NotifyOfPropertyChange("LatestAppointment");
  35.             }
  36.         }
  37.  
  38.         public void Save()
  39.         {
  40.             CommitChanges(_fileName);
  41.         }
  42.  
  43.         public void Load()
  44.         {
  45.             Initialize(_fileName);
  46.         }
  47.     }

Now, I realize this is a rather simple example of my previous post on YAGNI. But if I'd decided I wasn't going to utilize Caliburn due to the fact I only wanted to utilize it's binding features and I wasn't going to need all the "other stuff". I'd have had to spend the 20-30 minutes coding a "Get" method that took a default and looked at the isolatedstorage and saw if there was a setting and if not gave me a default, a save that saved all my settings back, and a any other method that I'm not thinking of that Caliburn already does for me. And then I'd have to support it when I realized I'd missed something. And even if they happen to miss something I need, I could still add it.

Moral of the story, make use of existing tools and you'll have the time to blog about it :-D

0

The finer points of YAGNI…

Posted by garrinmf on June 1, 2009 in Coding, Meanderings

I've ran into this a couple of times here recently both within my company with other dev's (a contract guy if that makes a difference) and in a number of comments on posts I've been reading.

The issue mainly arises with these finer points of YAGNI and pre-existing frameworks, be it open source or otherwise.

IMHO, YAGNI does NOT cover code you don't write. Explaining further, you can't throw out a "YAGNI!" when referring to using an existing framework as compared to rolling your own implementation of something. As always, there are exceptions. If it's a silverlight app and you need to keep the download small then you have some ground to argue from.

I'd much rather start using 10% of a tried and true framework with features that you THINK you'll never use than roll 100% of your own features and have to support those features. This is even MORE true when you find that what you THOUGHT was completely wrong thinking and you need that extra feature that the framework already implements. If it's part of a framework, chances are it's commonly used in combination with the rest of the features. Experience speaks truer than quick thoughts.

This also raises a whole other issue/post in why frameworks aren't used more. Very few other industries start from "scratch" with every project.

0

MySQL and precise numbers…

Posted by garrinmf on April 8, 2009 in Databases, TDD

FYI, if you're looking to deal with precise numbers and looking to store them in a MySQL database there are a couple things you need to know. I personally think this should be plastered all over the place, but thats me. If you go to the 'Numeric Type' page, it's not on there. That happens to be the first result (in my search) when googling for 'mysql numeric types' and the second result is 'Overview of Numeric Types'.

Now in my short life and limited experience, I've always found an "overview" to be more high level and less useful but here's the FYI that you'll ONLY find on the overview.

(FLOAT) A single-precision floating-point number is accurate to approximately 7 decimal places.

AND

(DOUBLE)A double-precision floating-point number is accurate to approximately 15 decimal places.

Now I've never dealt with such precise numbers when using other databases but this strikes me as a bit odd? Is it the norm for such things? I mean, essentially, what they're saying is that you can store ANY NUMBER YOU WANT, just don't expect to get back what you put in for any decimals over 7 places 'cuz we'll just make it up!! Seems odd to me, if you're only going to be precise to 7/15 digits, make that the limit because the crap after it is worthless anyways.

I ran into this because I was querying for exact numbers that I'd JUST inserted and not getting anything. I found that it was seemingly "randomly" rounding the numbers after so long and it took like 15 minutes of looking at documentation and googling to find the answer.

my 2 cents...

Copyright © 2006-2012 coding to music… All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.0.2, from BuyNowShop.com.