Quick Tip - Find elements in array

It’s great to learn something new everyday, especially if it involves Ruby. Usually when I’m searching for elements in an array, in PHP I would use in_array() to check for values in an existing array, for example. ( Thanks php.net )

$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
    echo "'12.4' found with strict check\n";
}

or looking for an array with an array

$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a))
    echo "'ph' was found\n";

'ph' was found

However Ruby has a cleaner syntax to check for values in an array ( isn’t that great :D )

in_my_array = [1, 2, 3, 4, 5, 6, 7] & [ 5, 1, 4]
=> [1, 4, 5]

Alright that’s your quick tip of the day, enjoy!

Local Development with Passenger

So I've finally dropped MAMP and decided to run Apache locally on my Mac. This was definitely a learning experience for me as it was only the second time that I've set up a web server. So here are my findings compiled into a recipe for you to use.

Hardware and Software

  • Mac OS X 10.6.8
  • Apache 2.2.21
  • MySQL 5.5.15
  • Rails 3.2.1
  • Ruby 1.9.3-p0
  • Ruby Version Manager 1.10.2
  • Homebrew 0.9

We don't have to worry about installing Apache, Mac OS X comes with it installed, so we can skip this step. The next order of business is to install homebrew for ease of installing packages for mac. So go to homebrew and install brew using this command

$ /usr/bin/ruby -e "$(/usr/bin/curl -fksSL https://raw.github.com/mxcl/homebrew/master/Library/Contributions/install_homebrew.rb)"

Once brew is installed we need to install wget so we can install other packages

$ brew install wget

Now we can install MySQL via Homebrew

$ brew install mysql

Once MySQL has finished installing you will presented with a bunch of important information to finish the installation of MySQL. If you forget something out of this information you can run this command to retrieve it.

$ brew info mysql

The current MySQL Homebrew recipe installs verison 5.5.20, but installs to a directory at 5.5.15 instead. So brew --prefix mysql shows us a directory pointing to 5.5.20, knowing this will save you a small headache.

We know can set up our mysql database with the previously mentioned hiccup applied here

$ unset TMPDIR
$ mysql_install_db --verbose --user=`whoami` --basedir="$(/usr/local/var/mysql/5.5.15)" --datadir=/usr/local/var/mysql --tmpdir=/tmp

MySQL is now installed! Lets start it up!

$ mysql.server start

And to shut it down.

$ mysql.server stop

So far so good, lets get Ruby Version Manager installed now. (Assuming you are using bash, zshell is not really that different)

$ bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer)
$ source ~/.bash_profile

Now we have RVM, lets install ruby, rails, and passenger

$ rvm install 1.9.3-p0
$ rvm use 1.9.3 --default
$ rvm gemset create rails321
$ rvm gemset use rails321 --default
$ gem install rails 3.2.1 --no-rdoc --no-ri
$ gem install passenger --no-rdoc --no-ri

Now we'll install the passenger module

$ passenger-install-apache2-module

You'll get a lot of prompts, but just follow the instructions and we'll continue the passenger installation. Passenger will ask you to modify your httpd.conf file, in order to do so you have to have root access. So navigating to the apache install and edit the file like so. You'll probably have to enter your root password.

$ cd /private/etc/apache2
$ sudo cp httpd.conf httpd.conf.bak
$ sudo vi httpd.conf (or whatever your editor of chocie is)

Then insert these lines into the httpd.conf file

LoadModule passenger_module /Users/username/.rvm/gems/ruby-1.9.3-p0@rails321/gems/passenger-3.0.11/ext/apache2/mod_passenger.so
PassengerRoot /Users/username/.rvm/gems/ruby-1.9.3-p0@rails321/gems/passenger-3.0.11
PassengerRuby /Users/username/.rvm/wrappers/ruby-1.9.3-p0@rails321/ruby

username is your root username

Personally I like to create a folder in the apache2 directory called mods-enabled and a file in the mods-enabled directory passenger.conf, then include that file via the httpd.conf, but the current method will suffice.

Ok lets create a new rails app in your webservers directory, mine is located at /Users/andredublin/Sites, but apache2 may have you pointing to /Library/WebServer/Documents, depending on the httpd.conf file.

$ rails new test.app.com -d mysql

Now we have to create the databases for our rails app.

$ mysql.server start
$ mysql
$ mysql> CREATE DATABASE test.app.com_development;
$ mysql> CREATE DATABASE test.app.com_test;
$ mysql> CREATE DATABASE test.app.com_production;
$ mysql> exit

Now go back your the apache2 directory at /private/etc/apache2 and we'll create a new folder called sites-enabled and we create a file called test.app.com

$ sudo mkdir sites-enabled
$ cd sites-enabled
$ sudo touch test.app.com

Ok now lets open and edit the test.app.com file with the following

$ sudo vi test.app.com

Make sure to point the DocumentRoot to the public folder in the rails app.

NameVirtualHost *:80

<VirtualHost *:80>
    ServerAdmin you@example.com
    ServerName test.app.com

    DocumentRoot /Users/username/Sites/test.app.com/public

    RailsEnv development

    <Directory /Users/username/Sites/test.app.com/public>
      AllowOverride all
      Options -MultiViews
    </Directory>

    ErrorLog /Users/username/Sites/test.app.com/log/error.log
    CustomLog /Users/username/Sites/test.app.com/log/access.log combined

</VirtualHost>

Now we can start our apache server with sudo apachectl start and navigate to test.app.com and viola! You have a rails app running on apache with passenger, give yourself a pat on the back. You can create multiple virtual hosts this way and have multiple instances of rails in tandem. If you come across any problems and improvements please leave a comment below.

Quick Tip - jQuery and ExtJS

Wow its been a while since my last update due to work and other coding activities. But I'm gonna hit you up with a quick tip I think you might find useful for front end development.

I am currently working on a project that requires me to use ExtJS. ExtJS is great for displaying data and creating professional looking apps. Their api documentation is incredible and the forum community is quite helpful, so it's easy for a noob of ExtJS to get started. But on to the quick tip.

I found that I needed to make multiple widgets on my web page, but ExtJS uses vanilla JS for DOM query selections. The problem here is that I lose out on the Sizzle engine that jQuery uses. It's easy to get jQuery and ExtJS to play nice together so lets make an index page that loads our scripts.

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery + ExtJS</title>
  </head>
  <body>
  <script src="jquery.js"></script>
  <script src="ext-debug-all.js"></script>
  </body>
</html>

Easy huh! Ok, now lets make some widgets and start our javascript that we'll drag and drop with ExtJS.

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery + ExtJS</title>
    <style type="text/css">
      .widget { width: 300px; height: 300px }
      #one { background-color: red }
      #two { background-color: blue }
      #three { background-color: green }
      #four { background-color: gray }
    </style>
  </head>
  <body>
  <div class="widget" id="one"></div>
  <div class="widget" id="two"></div>
  <div class="widget" id="three"></div>
  <div class="widget" id="four"></div>
  <script src="jquery.js"></script>
  <script src="ext-debug-all.js"></script>
  <script src="script.js"></script>
  </body>
</html>

Now the magic of jQuery and ExtJS as they work hand in hand will be created in our embbed script file

Ext.onReady(function() {
   var $widgets = $('.widgets');

   $widgets.map(function(index, elem) {
      var dd = new Ext.dd.DD(elem, 'widgetsDDGroup', {
         isTarget : false
      }):
      Ext.apply(dd);
   });
});

And we're done! We've just created a group of drag and drop widgets with the power of jQuery selectors and functions in tandem with ExtJS libraries. Enjoy for now, as I continue to work on this project I'll post some more tips for working with ExtJS and jQuery.

Mining Ruby - Enumerator Methods

And I’m back, its been a great Christmas holiday and New Year along with work keeping me quite busy. For my next installment of learning the Enumerator Class, I’ll be going over the methods that are available within. Let’s begin!

new : This is pretty obvious that this method will instantiate a new Enumerator object. In the example the first form is defined by the given block. Our “yielder” object is passed as a parameter and can be used to yield a value using the .yield method.

Example:

def incrementor(num)
  Enumerator.new do |yielder|
    number = num
    loop do
      yielder.yield(number)
      number += 1
    end
  end
end

start = incrementor(0)
=> #<Enumerator: #<Enumerator::Generator:0x007fa08c80f2a8>:each>

10.times do
  puts start.next
end
0
1
2
3
4
5
6
7
8
9
=> 10

As in my previous post we know that our enumerator will iterate over the block externally with .next and progress the sequence with each step.

The second form of .new (Which I believe deprecated as of 1.9.2p290 according to Programming Ruby 1.9, I could be wrong but ruby-doc.org doesn’t explicitly say when this happened) generates an Enumerator and iterates over the given object using the given method with the given arguments passed ref

Example from ruby-doc.org:

enum = Enumerator.new(ObjectSpace, :each_object)
=> #<Enumerator: ObjectSpace:each_object>

enum.select { |obj| obj.is_a?(Class) }
#=> returns an array of all classes

According to Programming Ruby 1.9 the later example should be done with to_enum call.

Modified example from ruby-doc.org:

enum_old = Enumerator.new(1..10, :each_with_index)
=> #<Enumerator: 1..10:each_with_index>
enum_old.to_a
=> [[1, 0], [2, 1], [3, 2], [4, 3], [5, 4], [6, 5], [7, 6], [8, 7], [9, 8], [10, 9]]

enum_new = (1..10).enum_for(:each_with_index)
enum_new.to_a
=> [[1, 0], [2, 1], [3, 2], [4, 3], [5, 4], [6, 5], [7, 6], [8, 7], [9, 8], [10, 9]]

Now lets move on to each_with_index, a method that I think to be very useful.

each_with_index : performs the same way as .each, but also appends and index argument when the block is called. This will return a new Enumerator if no block is given.

Example:

enum = (1..10).enum_for(:each_slice, 3)
enum.each_with_index do |subarray, index|
  puts #{index}: #{subarray}”
end
0: [1, 2, 3]
1: [4, 5, 6]
2: [7, 8, 9]
3: [10]
=> nil

That’s all for now, I’d like to keep this short and sweet so it’s easy for me and you the reader to absorb, next time I’ll be talking more about the methods available for the Enumerator Class.

Data Services

I hope everyone had a Merry Christmas and your preparing for the New Years!

I've been building an interest in data services since a seminar with the guys at Column 5 Media. So I'd like to share the links that I keep on hand for when I do start working with persistent or dynamic data with graphs and maps. Enjoy!

Economic

Broadband Statistics

Nasa

US Census

US Gov Dataservice

European Statistics

Geographical Names

International Data Resource Center

UN Statistical Organizations

NOAA Dataservice

Socrata - Public Dataservice

Another US Gov Dataservice

US Gov XML Data Sources

Mining Ruby - Enumerator.new Part Deux

Earlier this week I started talking about the Enumerator Class and Enumerable Module. From reviewing what I learned we know that the Enumerator Class allows you to store objects as enumerations. The advantage that we gain with enumerations is the ability to perform external iterations on the object, that is we are able to take something that is normally enumerable (performing iterations) and turn it into an object. In the case of Ruby I believe this will be Ranges, Hashes, Arrays, and even blocks.

Now we’ve already seen simple examples in my previous post but let’s get are hands dirty this time with enumerators and blocks. We can pass blocks to enumerators when they need to return a value, whats interesting about this is that the execution of the block happens in tandem with the enumerator object. So for example:

fib = Enumerator.new do |yielder|
  a, b = 0, 1 # parallel assignment
  loop do
    a += b # the same as a = a + b
    a, b = b, a # we swap values to prepare for the next iteration
  end
end
=> #<Enumerator: #<Enumerator::Generator:0x00000100a9b540>:each>

10.times { puts fib.next }
1
1
2
3
5
8
13
21
34
55

Fibonacci sequences are great for testing ideas, but the basic thought is that the block which calls our enumerator iterates over it externally and progresses the sequence with each step. Now lets pass a block to our enumerator that will return only the sum of even values of our Fibonacci sequence:

fib = Enumerator.new do |yielder|
  a, b = 0, 1 # parallel assignment
  loop do
    a += b # the same as a = a + b
    a, b = b, a # we swap values to prepare for the next iteration
  end
end
=> #<Enumerator: #<Enumerator::Generator:0x00000100a9b540>:each>

def even_fibbers(enum, &block) # &block lets us pass a block as a parameter
  Enumerator.new do |yielder|
    enum.each do |value|
      yielder.yield(value) if block.call(value)
    end
  end
end

puts even_fibbers(fib) { |num| num % 2 == 0}.first(10)
2
8
34
144
610
2584
10946
46368
196418
832040
=> nil

As we can see the enumerator was able to give us only the even Fibonacci values, successfully behaving as a filter for us in a very Ruby way. Well that’s it for today, I’ll wrap up next week with a review of methods for the Enumerator Class and Enumerable Module. Until then code strong.

Mining Ruby - Enumerator.new

Since my introduction to Ruby last summer at P2PU I’ve been frantically schooling myself in the way of Ruby and Rails. So I figured what better way than to extend my knowledge of Ruby by through self-explanations and research of the core libraries.

This series, which I so aptly named Mining Ruby, will start off with one of Ruby’s unique classes Enumerator. This will also include coverage of the Enumerable Module. So lets get started.

The Enumerator class allows you to store objects as enumerations and store the enumerated value in a variable to pass them as parameters and so forth. Whats really great about Enumerator is that the Enumerable Module returns an Enumerator object. This means we can chain methods together.

Taking a page from the ruby-doc.org.

# a non-block form  that still returns a Enumerator object
stooges = [Larry, Curly, Moe].each
=> #Enumerator: [“Larry”, “Curly”, “Moe”]:each

# tell us the class of the object
stooges.class
=> Enumerator

# invoke a block for each item to be enumerated
stooges.each_with_object(foo) |item,obj|
  puts #{obj}: #{item}”
end

# foo: Larry
# foo: Curly
# foo: Moe
=> foo

Whats really neat is that the non-block form will allow use to chain Enumerator methods together.

So for example.

stooges.each.each_with_object(foo) do |item,obj|
  puts #{obj}: #{item}”
end

# foo: Larry
# foo: Curly
# foo: Moe

As we see hear the .each method will return an Enumerator object which then is invoked by the .each_with_object method.

The Enumerator can also be used as an external iterator.

# %w is a shortcut notation for an array, no substitutions are performed on the string, such as \n or \t are not parsed
stooges = %w(Larry Curly Moe).each

3.times do
  puts stooges.next
end

Larry
Curly
Moe
=> 3

4.times do
  puts stooges.next
end

StopIteration: iteration reached an end

The .next method returns the next item in the enumeration. If we go past the last item in the object .next will Raise StopIteration Object.

So far we’ve covered a lot about the Enumerator class and how it works with objects so I’ll finish off with the public class method Enumerator.new (you know, since that’s the title of this post).

If you can guess Enumerator.new creates a new Enumerator object.

enum = Enumerator.new do |yielder|
  # code
end
=> #<Enumerator: #<Enumerator::Generator:0x00000100af7db8>:each>
# the 0x00000100af7db8 is a memory address and will be different with each instance of an object

In the example above notice that the block is initialized and there is a Enumerator object wrapper around our Enumerator block. This allows us to call the block when needed and yield or in my php mindset echo the code in the block. Lets put the enum variable to work.

def num_to_array(number)
   enum = Enumerator.new do |yielder|
     yielder.yield number
   end
   enum.take(number)
end

num_to_array(3)
=> [3]

Here our Enumerator object is waiting inside a method to be called. When called the block is passed an object class Enumerator::Yielder we then use the yield method of this class to return an enumeration. Enumerator::Yielder also has a '<<' method which performs the same action as yield.

Well thats it for now, I'll be diving further into the Enumerator class and Enumerable module later this week.