Brandon Harris |

Populate Object Instance Variables From Hash

I recently needed to write a class in ruby that I wanted to behave similarly to an ActiveRecord based class, but without the database ties. Particularly, I wanted to do this:

1 r = Record.new({:attribute1 => "a", :attribute2 => "b"})

It’s not too hard to hard code a simple class with attributes that are defined by a Hash, but in the pursuit of elegance, I wanted it to be more generic. I pulled up this little snippet:

1   attributes.each do |k, v|
2     if k.include?("(")
3       multi_parameter_attributes << [ k, v ]
4     else
5       respond_to?(:"#{k}=") ? send(:"#{k}=", v) : raise(UnknownAttributeError, "unknown attribute: #{k}")
6     end
7   end

This is your most basic metaprogramming technique in ruby. Check if the object responds to the message, and if so, set it.

Below is all that I needed to accomplish my task:

1   def initialize(attributes={})
2     attributes.each do |k,v|
3       respond_to?(:"#{k}=") ? send(:"#{k}=", v) : raise(NoMethodError, "Unknown method #{k}, add it to the record attributes")
4     end
5   end

Watch E Text Editor on Linux

Now that e – text editor has been opened up, I am anxious to see it running on linux. It looks like there is some activity on github. I cloned it myself and will be tinkering with it.

A lot of people will say, “Who needs another editor? Use Vim or Emacs.” I personally prefer the cramped finger inducing keystrokes of Emacs, but I am always willing to play around in another editor. I found TextMate to have a very fluid feeling that a lot of editors seem to be missing, the drawback is that I am not willing to pay Apple premiums so I can run TextMate. Macs are great, but I am far too frugal to spend the money on one. I am also irritated by The TextMate developers approach to their precious editor. I can understand the Mac-only rationality from a small business perspective, but their entire approach reeks of Apple fanboyism. I am willing to wager that a lot of linux developers would pay for TextMate, I know that I would. Alas, I am resolved to search for alternatives.

I spent some time using Gedit, which can be setup to be TextMate-like. I liked that environment, but I was instinctively pulled back to emacs. Muscle memory is a terrible beast to overcome.

My hopes are high for e. At the very least it is nice to watch the simple editor world evolve. Now I am off to play with the e source code.

Tags

  • e (1)