Monthly Archives: February 2013

RubyTapas – Free Episode Trial

http://devblog.avdi.org/rubytapas-episode-list/

Just watched a couple of screencasts in the above. Nice. There’re just too many useful resources around there, and I need more time to check them around!

Some notes are,

[Barewords]
http://devblog.avdi.org/2012/10/01/barewords/
This episode talks about changing variable scopes without affecting the code which refers to the variable. In ruby, signatures of method and instance variables are identical. If variables are reffered through accessors, it becomes flexible and easily extended. It would be a good example for showing the advantage of using “var_name” accessors instead @var_name.

[Command-Query Separation (CQS)]
http://devblog.avdi.org/2012/10/22/rubytapas-episode-13-singleton-objects/
This episode talks about CQS which is a practice to seperate command methods (change states) and query methods (get states). Having a method with these two aspects makes the code complex, and it’s good practice to separate them out.
The concept is understandable, and maybe this episode shows an good example that mixing these 2 makes it difficult to test each aspect separately. But, in ruby world, there’re many methods that do both, as every method returns value. I’m yet having difficulty to judge what’s good and what’s not. I may need more learning on this point.

AngularJS – Directive(2)

A little more study on directive. Getting more understanding, but feeling more deeper complexity.

  • “compile” and “link” function have similar functionalities, but it becomes different when “ng-repeat” is applied along with it. “compile” is called only once, but “link” is called multiple times. It’s because compile is applied for its template. The “link” is applied for each instances. Use “link” instead of “compile” unless you want to modify template.
  • $scope.watch allows to monitor properties change and it provides a binding functionality for the variables. It can be used within the link functions or controllers.
  • $scope.apply can tell angular about the change occured outside of angular world (e.g. click event).

The following is some exercise I made. It’s just about updating image and text, when drop-down selection is changed.

<html ng-app="app">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular-resource.min.js"></script>
    <script>
      app = angular.module('app', ['ngResource']);
      app.directive('icon', function($parse) {
        return {
          link: function(scope, element, attr) {
            //watch scope.iconName through attr.icon variable, and update the text.
            scope.$watch(attr.icon, function(name) {
              element.text("current selection is '" + name + "'. Click this text to reset. ");
            });

            //bind click event to update scope.iconName through attr.icon variable.
            element.bind('click', function() {
              scope.$apply(function() {
                $parse(attr.icon).assign(scope, scope.iconList[0]);
              });
            });
          }
        }
      });

      function IconCtrl($scope) {
        // list of icon-name shown in the dropdown-list
        $scope.iconList = ["arrow_circle_225", "broom"];
        $scope.iconName = $scope.iconList[0];

        $scope.$watch('iconName', function(name) {
          //based on the drop-down selection, updates the icon image by updating $scope.iconUrl variable
          $scope.iconUrl = "http://cdn1.iconfinder.com/data/icons/fugue/icon_shadowless/" + $scope.iconName + ".png";
        });
      }
    </script>

    <style type="text/css">
      .icon-name {
        display: inline;
      }
    </style>
  </head>
  <body ng-controller="IconCtrl">
    <div>
      <select
          ng-model="iconName"
          ng-options="icon for icon in iconList">
      </select>
      <br/><br/>

      <img ng-src="{{iconUrl}}"/>
      <div icon="iconName" class="icon-name"/></div>
    </div>
  </body>
</html>

Metaprogramming Ruby: Program Like the Ruby Pros

http://www.amazon.com/Metaprogramming-Ruby-Program-Like-Pros/dp/1934356476

Learning Ruby’s meta-programming. Though I knew the concept, I didn’t have a chance to apply them on actual coding. This book covers various meta-programming techniques with nice exercises (not boring) and actual practices (using rails codes as examples), and it was good exercise for me to organize my thoughts.

The most major one for ruby may be the “method_missing”, and the following is my trial for immitating :attr_accessor.

class Base
  def self.accessors(*attrs)
    @@getters = attrs
    @@setters = attrs.map { |x| "#{x}=".to_sym }
  end

  def method_missing(action, *args)
    if @@getters.include?(action)
      instance_variable_get("@#{action}")
    elsif @@setters.include?(action) and args.length >= 1
      instance_variable_set("@#{action.to_s.chop}", args[0])
    else
      super
    end
  end

  def respond_to?(action)
    if (@@getters + @@setters).include?(action)
      true
    else
      super
    end
  end
end

class Profile < Base
  accessors :name, :age
end

obj = Profile.new

obj.name = "John"
p obj.name
  # => "John"

p obj.age
  # => nil

obj.age = 20
p obj.age
  # => 20

begin
  obj.something
rescue => e
  p e
    # => #<NoMethodError: undefined method `something' for #<Profile:0x007f7fd204dfb8 @name="John", @age=20>>
end

p obj.respond_to?(:age)
  # => true
p obj.respond_to?(:something)
  # => false

Also, I found the following example interesting. “instance_eval” can break encapsulation of private methods.

class MyClass
  def public_method
    puts "It can be called"
  end
private
  def private_method
    puts "It should not be called, but..."
  end
end

obj = MyClass.new

obj.public_method
  # => "It can be called"
begin
  obj.private_method
rescue => e
  puts e
  # => private method `private_method' called for #<MyClass:0x007f920204fe20>
end

obj.instance_eval { private_method }
  # => It should not be called, but...

AngularJS – Directives (1)

I couldn’t understand how/when to use directives in the first place. So, I’ve tried on the above video. It has nice explanations and examples. As I understood, directive brings a function into HTML world through extending a tag or its attributes. It’s a similar concept as functions in standard programming languages, which provides a way seperating out a duplicated logics into shared templates.

What I’ve learned about directives are are as follows.

  • “template” attributes allows to directly defining templating HTML tags, or you can use “templateUrl” for rendering partials in the file.
  • If “transclude” is set true, you can include “ng-tranclude” in the template.
  • Setting “scope” attribute makes own scope in the directive. If setting a attribute with “@” mark, allows to read scope attributes.

And, the following is a exercise I’ve tried so far.

<html ng-app="app">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular-resource.min.js"></script>
    <script>
      app = angular.module('app', ['ngResource']);
      app.directive('icon', function factory() {
        return {
          restrict: 'E',
          scope: {
            name: '@'
          },
          template:
            '<div class="icon">' +
            '  <img src="http://cdn1.iconfinder.com/data/icons/fugue/icon_shadowless/{{name}}.png"/>' +
            '  <div class="icon-name" ng-transclude>' + '</div>' +
            '</div>',
          replace: true,
          transclude: true
        }
      });
    </script>

    <style type="text/css">
      .icon-name {
        display: inline;
      }
    </style>
  </head>
  <body>
    <div>
      <icon name="arrow_circle_225">Arrow Circle</icon>
      <icon name="broom">Broom</icon>
    </div>
  </body>
</html>

The <icon> tag is expanded as follows, and it shows icon image along with the name inside the <icon> tag.

<div class="icon" name="arrow_circle_225">
  <img src="http://cdn1.iconfinder.com/data/icons/fugue/icon_shadowless/arrow_circle_225.png">
  <div class="icon-name" ng-transclude="">
    <span class="ng-scope">
      Arrow Circle
    </span>
  </div>
</div>

Learning AngularJS

Started learning AngularJS. I had once tried several sample codes of client JS frameworks like Ember.js, Backbone.js, etc. , but I didn’t have a chance to go above them. Maybe after watching the railscast – #405 AngularJS last week, it triggered something in my mind for start learning it.

As a trial, I just applied a client-side search into the HTML of kindle-your-highlights. Though it’s a very simple one yet, I had to struggle with the magical world which AngularJS provides.

Most of the AngularJS’s demonstration starts from simple by-directional binding with a textbox and a label working together. But, as it goes into “templates” and “directives”, it’s getting difficult to understand how it’s working. It may mostly be due to my lack of knowledge in HTML/DOM and JavaScripts, but I’m having difficulties to understand the concept of “dependency injection” and where/how methods are being called.

Anyway, maybe I’ll be trying a little more.

Testing Codes

Another notes after reading “Object-Oriented Design in Ruby”, regarding testing section.

Changeability is one important design metric, and appropriate testing code asissts them through performing refactoring or avoiding unexpected regression. But, too much testing code can increase costs to maintain or change the testing code itself. Therefore, “What should be tested” and “What should NOT be tested” needs to be carefully designed. But there’re not definitive answers for that, and it’s rather a design decision. In practice, most programmers tend to write too many tests.

The followings are some examples that should not be tested.

[Private Methods]
Tests should concentrate on the incoming or outgoing messages that cross an object’s boundaries. Test for private methods are redundant and unstable, which both increases the costs for maintenances.

[Query Methods]
Outgoing messages that just gets information from the receiver with no side-effect is called query methods, and should not be tested by the sending object. It’s part of the receiver’s public interface, and testing in both sides duplicates the testing codes.

In the book, MiniTest was used for showing examples. One example was to use Modules for sharing testing. “RSpec” seems to have similar concept through shared_examples statement as follows. It’s nice.

require 'rspec'

class Mechanic
  def prepare_trip
    "prepare bicycle..."
  end
end

class Driver
  def prepare_trip
    "prepare vehicle..."
  end
end

shared_examples_for "trip" do
  it "should respond to prepare_trip" do
    subject.should respond_to(:prepare_trip)
    subject.prepare_trip.should_not be_nil
  end
end

describe 'Mechanic' do
  let(:mechanic) { Mechanic.new }
  include_examples "trip" do  # with parameter
    let(:subject) { mechanic }
  end
end

describe 'Driver' do
  let(:subject) { Driver.new }
  include_examples "trip"  # without parameter
end

Array.transpose

Didn’t know the Array.transpose method to create transposed matrix. Nice.

def calc(ary)
  ary.join(" + ") + " = " + ary.reduce(&:+).to_s
end

ary = [[4,9,2],[3,5,7],[8,1,6]]

puts "[row]"
puts ary.map {|a| calc(a) }
  # => 4 + 9 + 2 = 15
  # => 3 + 5 + 7 = 15
  # => 8 + 1 + 6 = 15

puts "[column]"
puts ary.transpose.map {|a| calc(a) }
  # => 4 + 3 + 8 = 15
  # => 9 + 5 + 1 = 15
  # => 2 + 7 + 6 = 15

Inheritance and Composition

A little more notes after reading “Object-Oriented Design in Ruby”, regarding inheritance and composition.

Composition is the good selection in the most cases, where you don’t have a clear view that the inheritance fits in. Inheritance requires all the subclasses to be the specialization of parent classes (is-a relationship). Otherwise, the structure can deteriorate during the future enhancements.

Composition is the more flexibile option to take. Though it requires additional codes for delegating methods, ruby’s Mix-in or Forwardable module can help implementing the delegation with a few lines of code.

require 'forwardable'

class A
  def a; "a is called"; end
  def b; "b is called"; end
  def c; "c is called"; end
  def d; "d is called"; end
end

class B
  extend Forwardable

  def initialize
    @a = A.new
  end

  def_delegators :@a, :a, :b # delegate methods through same name

  def_delegator :@a, :c, :e  # delegate methods with different name (c -> e)
  def_delegator :@a, :d, :f  # delegate methods with different name (d -> f)
end

b = B.new
puts [b.a, b.b, b.e, b.f].join(", ")
 # => a is called, b is called, c is called, d is called

From a practical point of view, an design metric that matters most is the change cost in the future. If the change cost hit a threshold, changes cause unexpected defects, development speed slows down, and then the death spiral begins. Though we cannot always know what changes can happen in the future, we should guess and make design decision at some point. The composition is a safer way to go in the unclear eye-sight, and also Ruby provides a neat implementation sharing through Mix-in and Forwardable.

Changes and Dependencies

Notes after watching the following video. Nice one.

Dependency management is an important factor for writing stable codes. Just a complex implementation does not always cause bad dependencies. Knowledges communicated among classes through message, variables and namings are the factor for adding dependency. As long as complicated or unstable implementations are hidden within the class, it may not cause large problems and could be left alone.

[Points]
1. Exposing stable public APIs
2. Hiding private behaviors
3. Minimizing the codes unrelated to the class
4. Moving out the rest (unrelated and unstable ones)

Mix-in Example

Just trying to create an example for the mix-in use.

class Days
  include Enumerable

  def initialize(days = [])
    @days = days.map {|x| Day.new(x) }
  end

  def << (day)
    @days << Day.new(day)
  end

  def each
    @days.each do |day|
      yield day
    end
  end

  def to_s
    @days.join(", ")
  end
end

class Day
  include Comparable

  def initialize(day)
    @day = day
  end

  def <=> (other)
    get_index(@day) <=> get_index(other.to_s)
  end

  def +(x)
    index = (get_index(@day) + x) % DAYS.length
    DAYS[index]
  end

  def to_s
    @day
  end

private
  DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

  def get_index(str)
    DAYS.index(str.capitalize)
  end
end

puts "[Compare]"
puts Day.new("Sat") < Day.new("Mon")
# => false
puts Day.new("Wed") > Day.new("Tue")
# => true

days = Days.new(["Wed", "Mon", "Tue", "Sun"])
days << "Sat"

puts "[List]"
puts days
# => Wed, Mon, Tue, Sun, Sat

puts "[Sort]"
puts days.sort.join(", ")
# => Sun, Mon, Tue, Wed, Sat

puts "[Select]"
puts days.select { |x| x >= "Tue" }.join(", ")
# => Wed, Tue, Sat

puts "[Map]"
puts days.map {|x| x + 1 }.join(", ")
# => Thu, Tue, Wed, Mon, Sun

puts "[Max]"
puts days.max
# => Sat