Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

Thursday, April 9, 2015

OOP Setters Can be Used to Emulate Partial Application

Recently I was asked an awesome question that went something like
How would you do something like high-order functions and partial application in object-oriented programming?
For high-order function my mind immediately jumped to Guava's Function Interface. I said, "hmmmm, let's see, could have some method (maybe called partiallyApply) that took an argument and returned another Function." In retrospect, this may have been overly complex, and a much simpler implementation of Function may work just as well in this case: fluent setters.

Let's look at a contrived, dead-horse-esque example. A partial function that does addition on two arguments.

In Haskell, if I wanted to build such a function, and partially apply it to, let's say 5, I might do the following
add5 = (+) 5

add5 10 -- is 15
In Clojure, this might look like
(def add-5 (partial + 5))

(add-5 10) ; is 15
So, how would I do this using setters? Simple! Here's some Ruby code
class Adder
  def value(first)
    @first = first
    self
  end

  def to(second)
    @second = second
    self
  end

  def add
    @first + @second
  end
end

adder_of_5 = Adder.new.value(5)

adder_of_5.to(10).add # is 15
This code (obviously) has a lot more ceremony wrapped around it, but it does achieve some of the same benefits as partial application (e.g. laziness, partial parameter fulfillment). The point is, if this were Java code, I could easily implement Function and change add to invoke and have a partial function in an object-oriented system.

Wednesday, August 27, 2014

Quicksort in Ruby

Just wanted to open up some code for examination and/or (hopefully) ridicule. Here's a recent quicksort implementation in Ruby that I threw together:

class Array
  def quick_sort
    return self if count < 2

    pivot = pop
    parts = partition { |x| x < pivot }

    [*parts.first.quick_sort, pivot, *parts.last.quick_sort]
  end
end

It's pretty straight-forward and Ruby's expressiveness really does cause the code to closely resemble the algorithm.

Sunday, July 20, 2014

Ruby Metaprogramming: class_eval

Lately I've been looking into ways of DRY-ing up ruby classes. One of the first, and perhaps most scarily powerful, is the class_eval method.

What does it do?

class_eval takes in a block or a string and executes it at the class-level. It's that simple!

Is it useful?

Yeah, it's scary useful. Here's an example where I define a bunch of similar methods on a class:

class Person
  ['age', 'name', 'favorite_color'].each do |attribute|
    ['with', 'and'].each do |prefix|
      class_eval %Q(
        def #{prefix}_#{attribute}(value)
          @#{attribute} = value
          self
        end
      )
    end
  end

  def to_s
    "Name: #@name, Age: #@age, Favorite Color: #@favorite_color"
  end
end

me = Person.new.
  with_name('Michael').
  and_age(22).
  and_favorite_color('Blue')

puts me.to_s # => Name: Michael, Age: 22, Favorite Color: Blue

This short little example used class_eval to define 6 methods on the person class: with_age, and_age, with_name, and_name, with_favorite_color and and_favorite_color! Pretty cool, huh?

Wednesday, May 7, 2014

Why I Dig RSpec

I've been using RSpec a fair amount lately, so I thought I'd talk about some of its features I really dig.

The rspec -f d command

If contexts and describes are favored over loaded setup and it blocks that do too much, you can get some really nice, verbose output from this command.

For example, suppose I have some specs describing a #wear_hat? method of a SimpleDecisions class. My rspec -f d output might look something like the following:

SimpleDecisions
  #wear_hat?
    when I am a vampire
      and it's sunny out
        returns true
      and it's night time
        returns false
    when I am at a home baseball game
      returns true
    when I am at an away baseball game
      and my hat is for my home team
        returns false

Pretty nice, huh? The specs almost match what we would expect the structure of the implementation to be!

Template specs

There's a lot of debate out there about whether test code should be DRY. Some say it shouldn't and that tests should flow and provide context. Others assert (no pun intended) that tests should be maintainable and, therefore, just as clean as (or cleaner than) production code. Template specs meet somewhere in the middle. They can replace many repeated tests at the (slight) expense of maintainability by looping through values and outcomes. For example, a template spec on an absolute value method might look like:

describe Math do

  describe '.abs' do
    [
      [42, 42],
      [0, 0],
      [-42, 42]
    ].each do |given_number, expected_number|

      context "given #{given_number}" do
       subject { described_class.abs(given_number) } 

       it { should be(expected_number) }
      end

    end
  end

end

In my mind, templates are nice when testing a pure function or when there are multiple, similar tests that can be aggregated.

Argument matchers

These are very cool. For example, say I want to test that an error is logged in a certain case, and I don't care about the specific error text, rather I just want the message to be some String. I could write something like this:

  # ...
  it 'logs an error' do
    ErrorLogger.should_receive(:write).with(kind_of(String))
    # cause error
  end
  # ...

This is a fairly trivial example, but these things are powerful. For a further example, presume ErrorLogger.write actually takes two parameters but I don't care about the second. The line would then become ErrorLogger.should_receive(:write).with(kind_of(String), anything).

Natural decoupling

By providing methods like subject and described_class and providing mechanisms to easily redefine the former, RSpec decouples the specs from things like the name of the class under test or the method being tested. For example, in my above absolute value example, if I changed the class from Math to MathUtils then, assuming everywhere below I referenced Math as described_class, I would only have to rename at the top of the file. One change in the production code would merit one change in the tests. Perfect!

Conclusion

Well, I hope I've expressed some of my favorite things about RSpec. If you would like to see any of my specs, they shouldn't be hard to find in my ruby repositories on github. If you have any comments on these points, or anything you really like about RSpec (or dislike for that matter) I'd love to hear your comments.

Saturday, April 19, 2014

Latest Project: froyo

First of all, let my sincerely apologize to anyone who stumbled upon this post looking for frozen yogurt. I beg your forgiveness, as this post contains neither frozen yogurt nor references to frozen yogurt other than those seen above.

Last month I wrote a short post on some of the benefits of using fluent interfaces. A slightly annoying element of implementing fluent interfaces is that fluent methods must return self. For example:
# ...
def im_fluent
  # Do stuff
  self
end

def me_too
  # Do stuff
  self
end
# ...
This annoys me not because its some form of duplication (tacking self on the end of each method is far from difficult to manage). Rather, I dislike this because it's not necessarily clear to programmers using this code that returning self enables the benefits of fluent methods. That's where the froyo gem (Fluent Ruby Objects Yo) comes in.

When a ruby class extends FroYo, it mixes-in the make_fluent method. make_fluent accepts the symbols (or string names) of existing method names and creates proxies that return self, leaving existing methods intact. The proxy methods are prefixed with an underscore. Without further ado, here's a simple, useless example:
require 'froyo'

class FunkyStringMaker
  extend FroYo

  def initialize
    @value = ''
  end

  def appending_funky
    @value.concat('funky')
  end

  def n_times_append_monkey(n)
    n.times { @value.concat('monkey') }
  end

  def blah
    @value = 'blah ' + @value
  end

  def to_s
    @value
  end

  make_fluent :blah, :n_times_append_monkey, :appending_funky
end

FunkyStringMaker.new.
  _appending_funky.
  _n_times_append_monkey(2).
  _blah.to_s # => 'blah funkymonkeymonkey'

As usual, all code is on my github.

Saturday, March 15, 2014

Fluent Interfaces (With Ruby Examples)

As of late, a hammer of mine has been the use of fluent interfaces. Fluent interfaces are simply classes that, instead of having methods that return something uninteresting or nothing, return the calling instance.

So, in a general, strongly-typed language this might look like:
public class Foo {
    public Foo FluentMethod() {
        // do some stuff
        return this;
    }
}

For simplicity's sake, I will use Ruby for the rest of this post. In the Ruby language this would look more like:
class Foo
  def fluent_method()
    # do some stuff
    self
  end
end

One of the biggest benefits of fluent interfaces is that they make change easier. For example consider the following, non-fluent code:
a_chicken = Chicken.new

mr_fox = Fox.new
mr_fox.is_quite(:fantastic)
mr_fox.lives_in(:a_tree)
mr_fox.eat(a_chicken)

This code annoys me (somewhat) because mr_fox appears on four lines, which implies that if you wanted to change it, you would have to change each of the four lines. Also, if I fat-fingered one of those references, I would waste time fixing it when the interpreter caught it. Here comes fluent to the rescue:
a_chicken = Chicken.new

Fox.new
   .is_quite(:fantastic)
   .lives_in(:a_tree)
   .eat(a_chicken)

Isn't that better? mr_fox doesn't even exist anymore. Also, in my humble opinion, this style of method chaining greatly improves readability.

There's also a hidden benefit in this example: fluent interfaces logically group operations of a single object onto, technically, one SLOC. For example, if I didn't use fluent method chaining, there's nothing stopping me from mixing Chicken logic with Fox logic:
a_chicken = Chicken.new
mr_fox = Fox.new
mr_fox.is_quite(:fantastic)
a_chicken.is_named("rodrick")
mr_fox.lives_in(:a_tree)
a_chicken.still_has_its_head(true)
mr_fox.eat(a_chicken)

But if I made Fox fluent and described it with method chaining then there's no way for me to interleave Chicken logic, and, frankly, create a mess:
a_chicken = Chicken.new
a_chicken.is_named("rodrick")
a_chicken.still_has_its_head(:eggs)

Fox.new
   .is_quite(:fantastic)
   .lives_in(:a_tree)
   .eat(a_chicken)

Of course, I (at this point in my software career) would probably make Chicken fluent as well, but I think it's fairly clear what that would look like at this point.

Hopefully you've come to dig fluent interfaces (at least a little) at this point. To me it's pretty cool that (in dynamic languages) implementing a fluent interface can be as simple as tacking a four-letter-word (self) on the end of methods whose return value we found otherwise uninteresting.

Wednesday, March 6, 2013

Communication between Python and Ruby Using Sockets

Sockets are a neat and (relatively) simple means of communication between different programs in a client-server relationship. They can also be used when it is necessary to communicate data between languages and speed is not a large issue.

The following code examples are a Python lyric server that I built and a Ruby client. Their full code is available on my github account.

simple_lyric_server.py (some implementation details hidden, see github for more):

import socket

 class LyricServer(object):
    def __init__(self):
        # Details hidden... See github

    def try_get_lyrics(self):
       
# Details hidden... See github

    def define_socket(self, port, n_requests=5):
        """
            Used to define the socket object from inputs
        """
        host = socket.gethostname()
        print "Lyric Thief Server: Hostname is %s" % str(host)
        self._socket.bind((host, port))
        self._n_requests = n_requests

    def handle_lyric_requests(self):
        self._socket.listen(self._n_requests)

        while True:
            client, address = self._socket.accept()
            print "Lyric Thief Server: Connected to %s" % str(address)

            self.lyrics = ''
            data = json.loads(client.recv(1024))
            try:
                self.artist, self.song = data['artist'], data['song']
            except KeyError:
                client.send("Invalid JSON passed")
                print "Lyric Thief Server: Invalid JSON Passed"
                client.close()
                return

            self.try_get_lyrics()

            # Try sending the lyrics line-by line

            for line in self.lyrics.split('\n'):
                client.send(line+'\n')

            print "Lyric Thief Server: Sent Lyrics, Closing Connection"
            client.close()

 

if __name__ == '__main__':
    server = LyricServer()
    server.define_socket(915, 5)
    server.handle_lyric_requests() 



So, quickly walking through what the methods do:
  • define_socket(self, port, n_requests=5) uses the properties attached to a socket object to construct the server's socket, where port is the port that the server will run on and n_requests specifies the maximum number of requests that the server can handle at once.
  • handle_lyric_request(self) tries to lookup (online) the lyrics of the song/artist pair JSON data that is passed in from a client and then send back an appropriate response.

Now looking at ruby_client.rb: 
require 'socket'

host = Socket.gethostname
port = 915

s = TCPSocket.new host, port
s.puts('{ "artist" : "Counting Crows", "song" : "Omaha"}')

lyrics = ""

begin
  while line = s.gets
    lyrics += line

  end
rescue
end 
s.close 

So, this Ruby client is much simpler. Essentially all it's doing is (1) building a new TCPSocket using the host machine and the same port as specified in the Python server, (2) writing a JSON object to the port (a request for the "Counting Crows" song "Omaha"), then it (3) reads in the lyrics and closes the connection.